I have below Jest config
jest: {
configure: {
testEnvironment: 'jsdom',
preset: 'ts-jest',
transform: {...},
moduleNameMapper: {
antd: '<rootDir>/__mocks__/antd/index.tsx'
},
testMatch: ['<rootDir>/src/**/*.test.(ts|tsx)$'],
},
},
In <rootDir>/__mocks__/antd/index.tsx
class Select extends Component<SelectProps> {
static Option: FC = (props) => <option {...props} data-testid="mock-selectOption" />;
render() {
const {
...props
} = this.props;
// @ts-ignore
return <select {...props} data-testid="mock-select" />;
}
}
I have a Select Component
import React from 'react';
import { Select as MySelect } from 'antd';
const { Option } = MySelect;
export interface SelectOption {
id: string;
label: string;
}
interface SelectProp {
options: SelectOption[];
selectedOption: string;
onChange: (key: string) => void;
}
function Select({ options, selectedOption, onChange }: SelectProp) {
return (
<MySelect value={selectedOption} onChange={onChange} >
{options.map((opt) => (
<Option key={opt.id} value={opt.id}>
{opt.label}
</Option>
))}
</MySelect>
);
}
export default Select;
I have a test case
import React from 'react';
import { fireEvent } from '@testing-library/react';
import { render } from 'setupTests';
import Select from './Select';
jest.mock('antd', () => {
const originalModule = jest.requireActual('antd');
return { ...originalModule };
});
describe('Select', () => {
const handleChange = jest.fn();
const mockProps = {
options: [],
onChange: handleChange,
};
it('render successfully', () => {
const { getByTestId } = render(<Select {...mockProps} />);
getByTestId('asca'); // use for debug
});
});
getByTestId('asca') will make the test case fails, then I see below DOM modal
TestingLibraryElementError: Unable to find an element by: [data-testid="asca"]
<body>
<div>
<select
data-testid="mock-select"
/>
</div>
</body>
which turns out still using the mock but not the actual antd component.
I've tried to add
beforeEach(() => {
jest.unmock('antd');
});
but still got the same result.
How can I use the actual module instead of mock?
Selectcomponent from./Selectrather thanantd