首页 > 解决方案 > 开玩笑 mockImplementation 总是返回 undefined

问题描述

我正在对一个模块进行测试。我需要嘲笑它。但是模拟函数的返回值总是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

解决方案


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

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

因此,mockImaplementation在行的前面移动后render,模拟函数正确返回。

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

推荐阅读