【发布时间】:2020-03-23 12:15:59
【问题描述】:
我正在测试一个函数,该函数在其中调用来自(es6 类)控制器的静态方法,该控制器返回 API 获取的结果。因为我正在编写一个单元测试并且控制器有自己的测试,所以我想模拟(技术上是假的)类中的静态方法来给我不同类型的响应。
// Controller.js
class Controller {
static async fetchResults() {} // the method I want to fake
}
// func.js - the function I am writing the test for
const func = async (ctx) => {
const data = await Controller.fetchResults(ctx.req.url)
if (containsErrors(data)) ... // do some logic
return { ...data, ...otherStuff }
}
这种伪造static async fetchResults() 的尝试没有任何作用,并且测试尝试调用原始控制器的fetchResults 方法。
// 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 });
});
});
下一次尝试似乎在某种程度上模拟工作,但返回值是undefined 而不是{ ...mockResponse, ...otherStuff },这表明整个类都被模拟了,但由于它找不到fetchResults是static 方法而不是实例方法。
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 });
});
});
【问题讨论】:
标签: javascript unit-testing mocking jestjs