简体   繁体   English

如何对该代码段进行单元测试?

[英]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). 我最近刚转到一个新项目,该项目主要使用Javascript(作为Node.js Web应用程序)进行交易。

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. 我是一名相当注重TDD的开发人员,并且正在尝试找出最佳方法/模式,以确保最终构建的产品可以进行单元测试和维护。

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? 我已经使用rewire.js库模拟了请求对象,并且可以成功测试是否调用了记录器,并使用正确的参数调用了该请求,但是我该如何完成测试覆盖范围?

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. 我已经为测试设置了参数,并且输入数据范围广(以确保所有代码行都可以在一个或另一个测试中执行),但是最后,在将回调参数传递给之后,它实际上并未执行回调参数。 rewire.js模拟。

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 回调正在执行,但是我需要在模拟程序中执行它,以确保仍然执行回调代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM