简体   繁体   中英

How to mock dependencies for testing in node.js?

我想为我的应用程序编写一些单元测试,我能以某种方式“模拟”与require('dependencyname')一起使用的一些依赖项吗?

You are looking for 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)
});

Straight out of their docs.

yes, for example with 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];
        })
    );
});

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