【问题标题】:Mock function in typescript打字稿中的模拟功能
【发布时间】:2018-07-13 13:49:46
【问题描述】:

我有以下代码要模拟:

const P = {
    scripts: {
        getScripts: (name?: any) => {
            // do some stuff and return json
            return { foo: 'value'};
        }
    }
}
export default P;

我需要测试的代码:

export const getScripts = (name?: string) => {
   return P.scripts.getScripts(name); // I want a mock being called here
};

我设法使用 sinonJS 进行测试:

const fakeGetScript = sinon.fake.returns({
    foo: 'fakeValue'
});

但我不知道如何用我的假货替换原来的getScriptP

有什么想法吗?

【问题讨论】:

    标签: typescript mocking mocha.js sinon


    【解决方案1】:

    Proxyquire 很好,但它不维护您的打字稿类型。 ts-mock-imports 是一个专门为用假货替换进口而设计的库,它建立在 sinon 之上。它也是类型安全的。

    【讨论】:

      【解决方案2】:

      您为什么不将P 作为协作者传递给更容易模拟,而不是使用proxyquire 拦截require

      export const getScripts = (name?: string, P) => {
         return P.scripts.getScripts(name); // I want a mock being called here
      };
      
      // Test
      const fakeGetScript = () => ({ foo: 'value' });
      const P = { scripts: { getScripts: fakeGetScript } };
      
      expect(getScripts('aName', P)).toEqual({ foo: 'value' });
      

      【讨论】:

        【解决方案3】:

        在这种情况下,您需要拦截您正在导入的模块的创建。诗乃无法做到这一点。实现此目的的一种方法是通过 proxyquire 库。

        它会是这样的:

        const proxyquire =  require('proxyquire');
        const fakeGetScript = sinon.fake.returns({
            foo: 'fakeValue'
        });
        const p = proxyquire('./path/to/p', {
          scripts: {
            getScripts: fakeGetScript
          }
        });
        

        然后你可以按照你的期望在 fakeGetScript 上运行你的断言。

        【讨论】:

        • 感谢您的回复,但您的解决方案与我正在寻找的解决方案接近,但由于我使用的是 import 而不是 require,看来 proxyquire 无法帮助我。跨度>
        • 没有矛盾。您可以将 proxyquire 用于您的测试模块(在您的测试模块中)。并在其他任何地方导入。
        • 好吧,我应该错过一些东西。我的代码像这样导入 P:import P from 'path/to/api' 据我了解,当使用 require 导入要模拟的对象时,proxyquire 注入假货@ 对不起,我的菜鸟问题,我在 JS 测试中真的很新,因此,在 TS 测试中...
        • 对,所以在你的测试代码中,不要做import P from 'path/to/api。相反,请执行const P = proxyquire('path/to/api', { ... })。您需要使用代理依赖项测试模块,而不是实际模块。
        • 不,你不需要。 Proxyquire 仅在测试代码中是必需的。就是在你的测试代码中,不是直接导入被测模块,而是需要使用proxyquire来导入。
        猜你喜欢
        • 2018-07-21
        • 2019-09-24
        • 2022-01-24
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 2021-06-30
        • 1970-01-01
        相关资源
        最近更新 更多