模拟使用不同值的useSelector

时间:2020-04-18 14:43:36

标签: javascript reactjs jestjs

我正在尝试这样的事情:

const useSelector = jest.fn();
jest.mock('react-redux', () => ({
  useSelector,
}));

然后尝试执行以下操作:

useSelector.mockReturnValueOnce({});
shallow(
  <ComponentUsingUseSelector />
);

那会给我一个错误:

jest.mock()的模块工厂不允许引用任何范围外的变量。

因此,如果我不能在模拟中使用超出范围的变量,那我将如何为每个测试返回不同的值?

2 个答案:

答案 0 :(得分:2)

在阅读了大量不符合我(认为)需要做的文章和文档之后,以下内容似乎可以工作:终于找到了一个。

import { useSelector } from 'react-redux';

jest.mock('react-redux', () => ({
  useSelector: jest.fn(),
}));


describe('some test', () => {
  it('do something', () => {
    useSelector.mockImplementation(() => ('hello world'));
    shallow(
      <ComponentUsingUseSelector />
    );

如果多次调用,我可以做:

describe('some test', () => {
  it('do something', () => {
    useSelector.
      .mockReturnValueOnce('first call')
      .mockReturnValueOnce('second call')
    shallow(
      <ComponentUsingUseSelector />
    );

答案 1 :(得分:1)

简化版,同样有效:

import * as redux from 'react-redux'

jest
  .spyOn(redux, 'useSelector')
  .mockReturnValueOnce('first call')

此外,与其依赖对 mockReturnValueOnce 的多次调用,不如仅存根存储的必要部分:

  const locale = 'en'

  const state = {
    application: { locale },
  }

  jest
    .spyOn(redux, 'useSelector')
    .mockImplementation((callback) => callback(state))