简体   繁体   中英

How to mock request module with rewire?

I have a custom module tokens.js with a function which makes requests via npm request module . It looks like this:

'use strict';

let request = require('request');

module.exports.getToken = function(code, cb) {
  let url = 'some_url';

  request(url, function (err, response, body) {
    if (err) {
      return cb(err);
    } else if (response.statusCode !== 200) {
      return cb('err');
    }

    parseGetResponse(body, function (err, token) {
      if (err) {
        return cb(err);
      }

      return cb(null, token);
  });
});

I'd like to write unit tests to cover getToken() function, but I have some troubles with mocking request module.

I tried this:

let mocha = require('mocha');
let rewire = require('rewire');
let should = require('should');

let requestMock = {
  request: function (url, cb) {
      // return cb(); etc
  }
}

let tokens = rewire('services/tokens.js');
tokens.__set__('request', requestMock);

But this approach doesn't work:

TypeError: request is not a function
  at Object.module.exports.getToken (services/tokens.js)

Actually, it leads to another question: How request module may works without directly calling exported function (request.request(url, cb)) ? And how should I use rewire with this?

Another option is to restructure the code so that its dependencies are easily configured.

function TokenGetter(request) {
   this.request = request || require('request');
   this.getToken = function(code, cb) { ...
}
module.exports.TokenGetter = TokenGetter;

// production code
var tokenGetter = new TokenGetter();

Test code

// test code can configure a mock request for your test, no 
// 3rd party libraries
// configure mockObject with assertions/return values
var mockRequest = function(url, cb) { .... ;

var testTokenGetter = new TokenGetter(mockRequest);

There are many strategies for making your classes configurable, and allowing the opportunity to inject fake objects for testing. I believe striving to write code for testability should eliminate the need to add even more 3rd party dependencies to your project.

Actually, I found a way to mock request module. I just make requestMock a function. Also I found out that in request module there is a line, that makes it possible: module.exports = request

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