reactjs 如何使用jest.mock为每个测试编写动态模拟数据

rjee0c15  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(207)

我正在模拟一个自定义钩子,虽然我可以在我的测试文件的顶部用静态数据来模拟,但我希望能够在每个测试的基础上进行模拟。例如,我希望能够在每个测试中返回不同的模拟数据。我将如何重新构造这个钩子,以便在每个测试中返回不同的数据呢?

const mocked_StartCapture= jest.fn()

jest.mock('@myModules/screen-hook', () => ({
  ...(jest.requireActual('@myModules/screen-hook') as any),
  useScreenHook: () => ({
    startCapture: () => mocked_StartCapture,
    viewableData: () => ({
      height: 1500,
      width: 1600,
      image:
        '00w0KGgoAAAANSUhEUgAAAGQiVBORAAABkBAMAAACCzIhnAAAAG1BMVEWJiob',
    }),
  }),
}))

test('renders Component', async () => {
 /// Update mock to use different startCapture and viewableData functions. 
  const result = render(<Screen/>)
  expect(result).toBeDefined()
})
5n0oy7gb

5n0oy7gb1#

你可以试试这样的方法:

cosnt mockViewableData = jest.fn.mockReturnValue({
  height: 1500,
  width: 1600,
  image: '00w0KGgoAAAANSUhEUgAAAGQiVBORAAABkBAMAAACCzIhnAAAAG1BMVEWJiob',
}));
const mockStartCapture = jest.fn();
jest.mock('@myModules/screen-hook', () => ({
  ...(jest.requireActual('@myModules/screen-hook') as any),
  useScreenHook: () => ({
    startCapture: () => mockStartCapture(),
    viewableData: () => mockViewableData(),
  }),
}));

然后在测试中:

test('renders Component', async () => {
  /// Update mock to use different startCapture and viewableData functions. 
  mockStartCapture.mockReturnValue({ whatever: "you need" });
  mockViewableData.mockReturnValue({ height: 42, width: 42, image: 'something' });

  const result = render(<Screen/>)
  expect(result).toBeDefined()
})

相关问题