【问题标题】:How to stub/mock submodules of a require of nodejs using sinon如何使用 sinon 存根/模拟 nodejs 要求的子模块
【发布时间】:2018-06-15 08:32:41
【问题描述】:

我使用 sinon 作为对 nodejs(Hapijs) 功能的单元测试。这个函数在 index.js 中。我将 index.js 包含在我的测试文件中作为

    var index=require('./index.js');

但在 index.js 内部还是需要

    var library= require('./library.js')

library.js 再次需要第三方功能

     var googlelib=require('googlelib')

现在当我在下面运行我的测试文件 testfunc.js 时

    var index= require('./index.js');
    var assert = require('assert');
    var sinon = require('sinon');
    var proxyquire= require('proxyquire');

我收到以下错误

    Error: Cannot find module './library'
    at Function.Module._resolveFilename (module.js:555:15)
    at Function.Module._load (module.js:482:25)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)

我想知道是否有任何方法可以对 index.js 的内部 require library.js 进行存根(因为 index.js 内部有很多需求,而且还有很多需求)

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js sinon


    【解决方案1】:

    您可以使用proxyquire 来存根所需的模块,像这样使用它。

    const proxyquire = require('proxyquire');
    
    const stubs = {
        './library': (some, argument) => {
            assert.equal(some, 'thing');
            return 'Some ' + argument;
        },
    };
    
    const index = proxyquire('./index', stubs);
    
    index();
    

    这将在index.js 中调用./library 时运行函数stubs['./library']

    如果library.js 导出一个带有函数的对象,只需让stubs 反映这一点,并确保调用它们在index.jslibrary.js 中的名称。

    const stubs = {
        './library': {
            more: (argument) => {},
            methods: (argument) => {},
        },
    };
    

    阅读文档以获取更多信息。将此与 MochaJasmine 等测试框架结合使用。

    另外,您得到的错误似乎不是来自您的测试文件,而是来自您的索引文件。这回答了您的问题,但您可能想查看导致错误的原因,或者更确切地说,为什么 index.js 找不到 library.js。确保它们在同一个文件夹中。

    【讨论】:

    • 我一直在阅读在 library.js 中调用的 const 文件。我正在考虑通过 proxyquire stubbs 做,但我仍然得到相同的 config not found 错误。
    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2014-04-02
    • 2021-09-22
    • 2019-04-03
    相关资源
    最近更新 更多