首页 > 解决方案 > 试图窥探一个模拟函数

问题描述

我正在尝试对模拟类中存在的函数执行 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

我尝试将模拟箭头函数更改为函数(),但这没有帮助。

我该如何设置它以便我可以监视我的模拟函数?

标签: reactjstypescriptjestjs

解决方案


使用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);
});

工作示例


推荐阅读