【问题标题】:mocking a require()'d imported object with jest/sinon用 jest/sinon 模拟 require() 的导入对象
【发布时间】:2017-10-06 20:52:47
【问题描述】:

这是我的代码:

const Config = require('Config');

export const getPayments = (username: string) => {

  if (username === undefined) {
    throw new Error('username is undefined');
  }

  const envEndpoint = Config.paymentsEndpoint;
  const endpoint: string = `${envEndpoint}/${username}`;

  return fetch(endpoint);
};

我要模拟的是 Config 对象。我基本上想在我的测试文件中拦截那个 require 调用,并将其替换为具有该 paymentEndpoint 值的对象。我正在使用 jest,但也有 sinon 作为模拟的选项。

我对单元测试和玩笑还是很陌生,所以如果我使用了不正确的术语,请原谅我

【问题讨论】:

    标签: unit-testing sinon jestjs


    【解决方案1】:

    在您的测试文件中在您导入您的getPayments 模块之前,您可以使用jest.mock 模拟配置模块。

    所以它看起来像

    /* getPayments.test.js */
    
    jest.mock('Config', () => {
      return { paymentsEndpoint: 'y' }; // return your fake Config obj here
    });
    
    import getPayments from './getPayments'; // or whatever the correct file path is
    
    describe(() => {
      [ ... your tests ]
    });
    

    这里是jest.mock 文档:https://facebook.github.io/jest/docs/en/jest-object.html#jestmockmodulename-factory-options

    【讨论】:

    • const Config = require('Config'); 在测试中不需要
    • 我认为这是一个正确的方向,但我现在收到这个错误:Test suite failed to run Cannot find module 'Config' from 'expertsApi.test.ts' at Resolver.resolveModule (node_modules/jest- resolve/build/index.js:179:17) at Object.<anonymous> (src/clients/expertsApi.test.ts:44:6) 另外,我很抱歉我忘了提到这是打字稿
    • 这很奇怪,看起来模拟可能无法正常工作。 ExpertApi.test.ts 是您定义模拟的文件吗?如果是这样,在 getPayments 导入上方定义的模拟是什么?
    • 好吧,所以this thread 说默认导出在 TS 中的工作方式不同 - 在模拟回调而不是 return YourFakeConfigObj; 中,你能试试 return { 'default': YourFakeConfigObj };
    猜你喜欢
    • 2015-11-10
    • 2017-08-01
    • 2019-12-17
    • 2019-10-24
    • 2019-07-22
    • 2018-06-30
    • 2019-06-22
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多