Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest snapshot testing React component with randomly generated id (uuid)

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();
  });
});
like image 231
Placid Avatar asked Mar 29 '18 01:03

Placid


1 Answers

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

like image 132
Andreas Köberle Avatar answered Oct 12 '22 21:10

Andreas Köberle