Nick Tomlin
Nick Tomlin

Reputation: 29211

Issues mocking node modules

I'm using superagent to back some XHR services in a react application. I've written a very thin wrapper around superagent to make configuration easier. Attempting to test this thin layer has proven to be quite the headache.

I'm aware that there are issues with jest and node core depdencies and I can get things to work by dontMocking superagent's dependencies. But i'd much prefer to have jest just mock superagent without blowing up by default.

The result is an extremely verbose test intro or unMockedModulePatterns entry in my package.json, is there a better way?

// my-module.js
'use strict';

var request = require('superagent');

module.exports = function () {
  return request.get('http://stackoverflow.com/questions/tagged/jestjs');
};

An example test:

// __tests__/my-module-test.js
'use strict';

jest.dontMock('../');
// T_T
jest.dontMock('superagent');
jest.dontMock('debug');
jest.dontMock('tty');
jest.dontMock('util');
jest.dontMock('stream');
jest.dontMock('fs');
jest.dontMock('delayed-stream');
jest.dontMock('mime');
jest.dontMock('path');

describe('mymodule', function () {
  var myModule, request;

  beforeEach(function () {
    myModule = require('../');
    request = require('superagent');

    request.get = jest.genMockFunction(function () {
      return {
        get: jest.genMockFunction()
      }
    })
  });

  it('makes an xhr request using superagent', function() {
    var req = myModule();
    expect(request.get).toBeCalledWith('http://stackoverflow.com/questions/tagged/jestjs');
  });
});

Upvotes: 4

Views: 2422

Answers (1)

user153275
user153275

Reputation:

I believe the better way is to write manual mocks, like so:

__tests__/codeundertest.js:

jest.dontMock('../codeundertest');
describe('whatever', function() {
  it('should do the do', function() {
    var request = require('superagent');

    require('../codeundertest')();
    expect(request.get.mock.calls[0][0]).toBe('http://stackoverflow.com/questions/tagged/jestjs');
  });
});

__mocks__/superagent.js:

module.exports = {
  get: jest.genMockFunction()
};

codeundertest.js:

var request = require('superagent');
module.exports = function () {
  return request.get('http://stackoverflow.com/questions/tagged/jestjs');
};

jest's automatic mocking is really nice when it works but there are many cases where it will be easier to write your own mocks than to try to prop up its automocking.

Upvotes: 6

Related Questions