Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

javascript - How to stub/mock submodules of a require of nodejs using sinon

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');

But again inside the index.js there is require

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

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

     var googlelib=require('googlelib')

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');

I get the below error

    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)

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

This will run the function stubs['./library'] whenever ./library is called in index.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) => {},
    },
};

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...