问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/48115128/how-to-stub-mock-submodules-of-a-require-of-nodejs-using-sinon