如何使用spyOn在jest中测试这段代码?有人能帮我找到合适的解决方案吗?
const controller = {};
controller.fetchCars = async (req, res) => {
const result = await getCarsService(req.body);
res.json(result);
};我试过这个:
it('fetchCars should call getCarsService', () => {
const spy = jest.spyOn(carsController, 'getCarsService').mockImplementation(() => {});
const req = {};
const res = {};
carsController.fetchCars(req, res);
expect(spy).toBeCalled()
spy.mockRestore();
});并给出以下错误:无法监视getCarsService属性,因为它不是一个函数;未定义的
getCarsService()是从/services导入的,如下所示:
export const getCarsService = async body => {
const carsReqConfig = {
headers: fetchApi.newHeaderWithToken(CAR_JWT, SITE_ID)
};
const result = await instance.post(
`${API_GATEWAY_URL}${CAR_ENDPOINT}/search`,
body,
carsReqConfig
);
const cars = result?.data?.results.filter(
car => car.orderType === 'AI'
);
const formatedResponse = formatCarSearchRes(cars);
return formatedResponse;
};发布于 2020-07-24 11:54:34
最简单的解决方案是将代码分离到每个文件中,然后只使用jest.mock来模拟getCarsService方法。
index.js
import getCarsService from './getCarsService';
const controller = {
fetchCars: async (req, res) => {
const result = await getCarsService(req.body);
return res.json(result);
},
};
export default controller;getCarsService.js
function getCarsService(body) {
return new Promise(resolve => resolve(1));
}
export default getCarsService;index.spec.js
import controller from './index';
import getCarsService from './getCarsService';
jest.mock('./getCarsService', () => jest.fn().mockResolvedValue(1));
it('fetchCars should call getCarsService', async () => {
const req = {
hello: 'world',
};
const res = {
json: jest.fn(),
};
await controller.fetchCars(req, res);
expect(getCarsService).toBeCalled();
expect(res.json).toBeCalledWith(1);
});如果你一心一意地使用间谍,你就可以通过监视默认出口来做到这一点。
import controller from './index';
import * as getCarsService from './getCarsService';
it('fetchCars should call getCarsService', async () => {
const req = {
hello: 'world',
};
const res = {
json: jest.fn(),
};
const spy = jest.spyOn(getCarsService, 'default');
spy.mockResolvedValue(2);
await controller.fetchCars(req, res);
expect(res.json).toBeCalledWith(2);
});https://stackoverflow.com/questions/63072511
复制相似问题