【问题标题】:jest mockImplementation always return undefined开玩笑 mockImplementation 总是返回 undefined
【发布时间】:2021-07-21 20:57:53
【问题描述】:

我正在测试一个模块。我需要嘲笑它。但是模拟函数的返回值总是undefined。以下是我的代码。

// foo.js
export const signin = () => {
  // some asynchronous code
  return Promise; // return a Promise value
};
// MyReactComponent
// What I want to test
import { signin } from './foo';
const MyReactComponent = () => {
  // a function which called when the signin button was clicked
  const onClickSignin = async () => {
    ...
    const result = await signin(); // 'result' is always 'undefined'

    result.ok; // Error ! result is 'undefined'
    ...
  };
};

我尝试了两种方法。

第一种方式

// MyReactComponent.test.js
import { signin } from './foo';
jest.mock('./foo', () => ({
  signin: jest.fn(() => true), // 'true' is just for checking if return undefined
}));

test('MyReactComponent', () => {
  ...
  expect(signin).matcher;
});

第二种方式

// MyReactComponent.test.js
import { signin } from './foo';
jest.mock('./foo', () => ({
  signin: jest.fn(),
}));

test('MyReactComponent', () => {
  ...
  singin.mockImplementation(() => true); // 'true' is also for checking
  expect(signin).matcher;
});

如何为这种情况应用模拟实现? (项目环境是create-react-app,叫CRA)

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    我找到了解决方案。 当我们测试一个反应组件时,测试中有一个render 部分。我在render之后写了mockImplementation

    test('...', () => {
      const {...} = render(<MyReactComponent />);
      ...
      singin.mockImplementation(() => true);
    });
    

    因此,将mockImaplementation 移动到render 行之前,模拟函数正确返回。

    test('...', () => {
      singin.mockImplementation(() => true); // move to here
      const {...} = render(<MyReactComponent />);
      ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2021-09-27
      • 2021-11-14
      • 2017-03-18
      • 2016-01-16
      相关资源
      最近更新 更多