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

后端 未结 1 735
灰色年华
灰色年华 2020-12-20 01:18

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 inde         


        
相关标签:
1条回答
  • 2020-12-20 01:21

    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.

    0 讨论(0)
提交回复
热议问题