简体   繁体   中英

Skip requiring a module for tests in Node.js

moduleOne:

const moduleTwo = require('moduleTwo'); //moduleTwo opens Websocket
module.exports = {
  functionToTest: () => 1
}

Now i want to test that function - test.js:

const tap = require('tap');
const moduleOne = require('moduleOne');

tap.equal(moduleOne.functionToTest(),1);

The problem is, that in moduleTwo some code is run that opens a websocket and the test does not finish.

How do i prevent moduleOne of requiring moduleTwo while testing?

You can use mock-require :

const tap = require('tap');
mock('moduleTwo', {
    // export whatever you need, just don't open websockets
});
// now moduleOne will require your mock instead of real moduleTwo
const moduleOne = require('moduleOne');
tap.equal(moduleOne.functionToTest(),1);

Or you can add some options to moduleTwo but it will require changing every place where it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM