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

帅比萌擦擦* 提交于 2019-11-29 12:44:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!