I am trying to create jest snapshot test for a React component that generates unique id using uuid. I am trying to mock the uuid functionality. But mocking does not seem to be working.
Component:
import React from 'react';
import v1 from 'uuid/v1';
class MyComponent extends React.Component {
// Other codes ...
render() {
const id = v1();
return (
<div>
<label htmlFor={id}>
<input type="checkbox"/>
</label>
</div>
)
}
}
export default MyComponent;
Test:
import React from 'react';
import renderer from 'react-test-renderer';
import MyComponent from './MyComponent';
describe('<MyComponent/>', () => {
it('renders correctly', () => {
jest.mock('uuid/v1', () => jest.fn(() => 1));
const tree = renderer.create(<Checkbox />).toJSON();
expect(tree).toMatchSnapshot();
});
});
The problem is that you mock the module after you import the module that you want to test. So the imported module has the original version of uuid/v1
imported. Then you mock uuid/v1
but this will have no effect on MyComponent
as this already have the reference to the original version.
When using jest.mock
in the most outer block of your test, it will be hoisted to the top of the module, so jest will mock uuid/v1
before it can be imported into MyComponent
that's why it works in this case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With