jestjs - 开玩笑 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)
解决方案
我找到了解决方案。当我们测试一个反应组件时,测试中有一个render
部分。我写了mockImplementation
之后render
。
test('...', () => {
const {...} = render(<MyReactComponent />);
...
singin.mockImplementation(() => true);
});
因此,mockImaplementation
在行的前面移动后render
,模拟函数正确返回。
test('...', () => {
singin.mockImplementation(() => true); // move to here
const {...} = render(<MyReactComponent />);
...
});
推荐阅读
- android - Android Studio:在try finally块中调用recycle时如何使用obtainStyledAttributes解决lint警告
- r - CRAN 包提交
- javascript - 如何在 React 中显示自动完成文本字段中的选定值?
- vb.net - 刷新图表区
- javascript - 防止大多数用户从网站下载视频文件的最佳做法
- c# - 这个抽象类是否有另一种方法可以从这个泛型类型派生?错误 CS0310
- java - 尝试使用 github 操作(maven)部署到 github 包时出现错误代码 400
- user-interface - 有没有办法在从 Firestore 生成的幻灯片/卡片上个性化 UI?扑
- bind - bind() 适用于 ipv6 无线适配器接口,但不适用于 ipv6 以太网(错误 10049)
- c# - 我应该使用 23:59:59 还是 00:00:00 表示 24 小时制的 12 AM?