4

I want to write some unit-tests for my applicatin, can I somehow "mock" some dependencies used with require('dependencyname')?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the input. Fixed my answer.
1

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];
        })
    );
});

1 Comment

Don't you think that suggesting a framework is a bit much on such a small use case? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.