首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用SpyOn进行Jest测试

用SpyOn进行Jest测试
EN

Stack Overflow用户
提问于 2020-07-24 11:19:21
回答 1查看 880关注 0票数 1

如何使用spyOn在jest中测试这段代码?有人能帮我找到合适的解决方案吗?

代码语言:javascript
复制
const controller = {};

controller.fetchCars = async (req, res) => {
  const result = await getCarsService(req.body);
  res.json(result);
};

我试过这个:

代码语言:javascript
复制
    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导入的,如下所示:

代码语言:javascript
复制
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;
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-24 11:54:34

最简单的解决方案是将代码分离到每个文件中,然后只使用jest.mock来模拟getCarsService方法。

index.js

代码语言:javascript
复制
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

代码语言:javascript
复制
function getCarsService(body) {
    return new Promise(resolve => resolve(1));
}

export default getCarsService;

index.spec.js

代码语言:javascript
复制
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);
});

如果你一心一意地使用间谍,你就可以通过监视默认出口来做到这一点。

代码语言:javascript
复制
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);
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63072511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档