【发布时间】: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