简体   繁体   中英

How can I unit test this code snippet?

I've just recently moved to a new project that deals mainly in Javascript (as a Node.js web application).

I'm a fairly TDD focused developer, and am trying to figure out the best approaches / patterns to ensure that what we end up building is unit-testable and maintainable.

I've been trying to wrap the following code snippet with unit tests, but am having trouble getting good code coverage over the anonymous function passed in as the request callback.

I have mocked the request object using the rewire.js library, and can successfully test that the logger was called, that request was called with the correct parameters, but how do I complete the test coverage for this?

function _makeRequest(apiName, options, payload, callback) {
  logger.info('DS API %s Request:\n  %s %s\n  %s', apiName, options.method, options.url, logger.look(payload));
  request(options, function(error, response, body) {
    var json = 'json' in options ? body : JSON.parse(body);

    if ('error' in json) {
      var msg = 'DS API ' + apiName + ' Error:\n  ' + logger.look(json.error);
      logger.info(msg);
      callback(null);
    } else { // no error
      logger.info('DS API %s Response:\n  %s', apiName, logger.look(json));
      callback(json);
    }
  });
}

Should I be refactoring for better testability? Is there a common approach for unit testing callbacks that I'm not aware of?

Carl put me on the right direction. I had set up my parameters for the tests with a good range of input data (to ensure that all code lines would be executed in one test or another) but, in the end, was failing to actually execute the callback parameter after passing it to the rewire.js Mock.

The callback was making it in, but I needed to execute it from within the mock to ensure that the callback code would still be executed

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