如何在Node.js中模拟依赖testing?

我想为我的应用程序编写一些unit testing,我可以以某种方式“模拟”require('dependencyname')所使用的一些依赖项吗?

您正在寻找Proxyquire 🙂

//file1 var get = require('simple-get'); var assert = require('assert'); module.exports = function fetch (callback) { get('https://api/users', callback); }; //test file var proxyquire = require('proxyquire'); var fakeResponse = {status:200}; var fetch = proxyquire('./get', { 'simple-get': function (url, callback) { process.nextTick(function () { callback(null, fakeResponse) }) } }); fetch(function (err, res) { assert(res.statusCode, 200) }); 

直接从他们的文档。

是的,例如用jest => https://facebook.github.io/jest/

 // require model to be mocked const Mail = require('models/mail'); describe('test ', () => { // mock send function Mail.send = jest.fn(() => Promise.resolve()); // clear mock after each test afterEach(() => Mail.send.mockClear()); // unmock function afterAll(() => jest.unmock(Mail.send)); it('', () => somefunction().then(() => { // catch params passed to Mail.send triggered by somefunction() const param = Mail.send.mock.calls[0][0]; }) ); });