如何使用sinon存根/模拟nodejs的require子模块 [英] How to stub/mock submodules of a require of nodejs using sinon

查看:185
本文介绍了如何使用sinon存根/模拟nodejs的require子模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用sinon作为单元测试nodejs(Hapijs)功能。此函数位于index.js中。我在我的测试文件中包含了index.js

I am using sinon as for unit testing a nodejs(Hapijs) functionality. This function is in index.js. I am include the index.js in my test file as

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

但是在index.js里面还有需要

But again inside the index.js there is require

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

同样,library.js需要第三部分功能

Again the library.js has the require of a third part functionality

     var googlelib=require('googlelib')

现在我在下面运行我的testfile testfunc.js

Now when I run my testfile testfunc.js below

    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的内部需求库.js(因为有许多需要内部索引) .js和许多要求的要求)

I would like to know if there is any way I can stub the inner require library.js of index.js (as there are many requires inside index.js and many requires of requires)

推荐答案

您可以使用 proxyquire ,像这样使用它。

You can stub a requried modules by using proxyquire, using it like this.

const proxyquire = require('proxyquire');

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

const index = proxyquire('./index', stubs);

index();

这将运行函数 stubs ['./ library'] 每当。 c> 中调用 ./ library

This will run the function stubs['./library'] whenever ./library is called in index.js.

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

If library.js exports an object with functions, just make stubs reflect that, and make sure to call them what they are called in index.js and library.js.

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

阅读文档以获取更多信息。将此与摩卡 Jasmine

Read the docs for more information. Use this in conjunction with a test framework like Mocha or Jasmine.

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

Also, the error you get does not seem to come from your test file, but rather your index file. This answers your question, but you might want to look into what is causing your error, or rather, why index.js can't find library.js. Make sure they are in the same folder.

这篇关于如何使用sinon存根/模拟nodejs的require子模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆