Problems with mocking node modules

I use superagent to return some XHR services to a responsive application. I wrote a very thin wrapper around the super agent to simplify the setup. Trying to test this thin layer turned out to be quite a headache.

I know that there are problems with the joke and node core files, and I can get the work to work by dontMocksuperagen dependencies. But I would prefer that the joke simply mocked superagentwithout exploding by default.

The result is a very verbose input or input unMockedModulePatternsin my .json package, 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');
};

Test example:

// __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');
  });
});
+4
source share
1

, - , :

__ __ /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');
  });
});

__ __/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 , , , , .

+6

All Articles