【发布时间】:2020-11-14 06:10:14
【问题描述】:
如何使用 spyOn 开玩笑地测试这段代码?有人可以帮我找到合适的解决方案吗?
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();
});
然后给我这个错误:Cannot spy the getCarsService property because it is not a function;改为未定义
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;
};
【问题讨论】:
-
该问题不包含最重要的部分,即 getCarsService 的来源。错误说明出了什么问题,你不能在它不属于的随机对象上窥探它。
-
我已经编辑了这篇文章,getCarsService 看起来像上面
标签: jestjs