reactjs - 试图窥探一个模拟函数
问题描述
我正在尝试对模拟类中存在的函数执行 spyOn:
test.ts -
import Service from '../base_classes/Service';
jest.mock('../base_classes/Service');
const o: Component = new Component();
it('should load model specific information', async () => {
const getSpy = jest.spyOn(Service.prototype, 'get');
let t = await o.load(1);
expect(t.name).toEqual('test_name');
expect(getSpy).toHaveBeenCalledTimes(1);
});
__mocks__/Service.ts -
export const mockGet = jest.fn(async () => Promise.resolve({name:
'test_name'}));
const mock = jest.fn().mockImplementation(() => {
return {
get: mockGet
}
});
export default mock;
产生的错误是:Cannot spy the get property because it is not a function
我尝试将模拟箭头函数更改为函数(),但这没有帮助。
我该如何设置它以便我可以监视我的模拟函数?
解决方案
使用jest.mock
它时,它会自动为模块的每个属性创建一个模拟,将其功能替换为jest.fn()
(没有实现)。从那时起,您可以编写断言。您应该没有理由要监视模拟函数,因为它已经是模拟函数。
您应该监视实际实现或为模拟模块上的方法编写断言。
例如
it('should load model specific information', async () => {
let t = await o.load(1);
expect(t.name).toEqual('test_name');
expect(Service.mock.instances[0].get).toHaveBeenCalledTimes(1);
});
推荐阅读
- apache-spark - 方案没有文件系统:Hadoop 3.2.1 中的 wasbs 错误
- symfony - Symfony 4:手动连接数据库/创建动态实体管理器
- java - Android导航组件:返回上一个屏幕而不丢失状态
- python - 无法多次获取mysql结果
- angular - 快速滚动时出现滚动问题,特别是在响应模式和设备上
- internationalization - i18n-node:为一种语言分成多个文件
- java - Eclipse:“找不到 Java SE 运行时环境”
- swift - “(null)”想使用“google.com”登录
- r - 将 ggplot geom_polygon 扩展到绘图末尾
- php - ajax 请求的动态 URL