Javascript 在Jest中为es6类的静态方法创建mock实现
我正在测试一个函数,该函数在内部从es6类控制器调用一个静态方法,该控制器返回API获取的结果。因为我正在编写一个单元测试,并且控制器有自己的测试,所以我想从技术上模拟类中的静态方法,以给我不同类型的响应Javascript 在Jest中为es6类的静态方法创建mock实现,javascript,unit-testing,mocking,jestjs,Javascript,Unit Testing,Mocking,Jestjs,我正在测试一个函数,该函数在内部从es6类控制器调用一个静态方法,该控制器返回API获取的结果。因为我正在编写一个单元测试,并且控制器有自己的测试,所以我想从技术上模拟类中的静态方法,以给我不同类型的响应 // Controller.js class Controller { static async fetchResults() {} // the method I want to fake } 这种伪造静态异步fetchResults的尝试没有任何作用,测试尝试调用原始控制器的fetc
// Controller.js
class Controller {
static async fetchResults() {} // the method I want to fake
}
这种伪造静态异步fetchResults的尝试没有任何作用,测试尝试调用原始控制器的fetchResults方法
下一次尝试看起来好像mock在某种程度上正常工作,但返回的值未定义,而不是{…mockResponse,…otherStuff},这表明整个类正在被模拟,但找不到fetchResults,因为它是一个静态方法而不是实例方法
import Controller from './Controller.js'
describe('when data is successfuly fetched', () => {
Controller.mockImplementation(jest.fn(() => ({
fetchHotel: () => { ...mockResponse, ...otherStuff }
})
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});
你可以用它来做这件事
例如
controller.js:
导出类控制器{
静态异步fetchresultsrl{
返回{result:'real result'};
}
}
func.js:
从“./Controller”导入{Controller};
const func=async ctx=>{
const data=await Controller.fetchresultstx.req.url;
//做些逻辑分析
返回{…数据};
};
导出{func};
func.test.js:
从“./Controller”导入{Controller};
从“/func”导入{func};
描述'60776211',=>{
它“应该通过”,异步=>{
const fetchResultsSpy=jest.spyOnController'fetchResults'。mockResolvedValueOnce{result:'fake data'};
const ctx={req:{url:'example.com'};
常量实际值=等待函数x;
expectactual.toEqual{result:'假数据'};
fetchResultsSpy.mockRestore;
};
};
单元测试结果和覆盖率报告:
通过stackoverflow/60776211/func.test.ts
60776211
✓ 应该超过5毫秒
--------|-----|-----|-----|-----|----------
文件|%Stmts |%Branch |%Funcs |%Lines |未覆盖的行
--------|-----|-----|-----|-----|----------
所有文件| 91.67 | 100 | 75 | 88.89 |
controller.ts | 80 | 100 | 50 | 75 | 3
函数ts | 100 | 100 | 100 | 100 |
--------|-----|-----|-----|-----|----------
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:4.922s,估计11s
// func.test.js
describe('when data is successfuly fetched', () => {
jest.mock('./Controller.js', () => jest.fn().mockImplementation(() => ({
fetchResults: jest.fn(() => mockResponse),
});
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});
import Controller from './Controller.js'
describe('when data is successfuly fetched', () => {
Controller.mockImplementation(jest.fn(() => ({
fetchHotel: () => { ...mockResponse, ...otherStuff }
})
it('returns correct information', async () => {
expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
});
});