Jest 快照测试具有随机生成的 id (uuid) 的 React 组件

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

我正在尝试为使用 uuid 生成唯一 ID 的 React 组件创建笑话快照测试。我正在尝试模拟 uuid 功能。但是嘲笑似乎没有用。

组件:

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;

测试:

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();
  });
});

问题是您在导入要测试的模块后模拟了该模块。所以导入的模块导入了 uuid/v1 的原始版本。然后你模拟 uuid/v1 但这对 MyComponent 没有影响,因为它已经引用了原始版本。

在测试的最外层使用 jest.mock 时,它会被提升到模块的顶部,所以 jest 会在导入 [=12] 之前模拟 uuid/v1 =] 这就是它在这种情况下起作用的原因