0

示例代码:

function TestClass() {
  var this.name = 'test';
  var this.host = '...';
  var this.port = '...';
  //...
  this.connection = this.createConnection(....);
}

TestClass.prototype.testFunc = function(data) {
  if(data == this.name) {
     return true;
  } else {
     return false;
  }
}

Testclass.prototype.createConnection = function (...) {
   //some code
  //a real HTTP connection will be created
  //some code
}

现在我想测试 testFunc,它有一个类变量this.name,所以我必须创建一个 TestClass 实例。但是如果我创建 TestClass 实例,就会创建一个真正的 HTTP 连接。测试时如何避免这种真正的 HTTP 连接?

在这种情况下,我该如何编写测试代码?

4

2 回答 2

0

您应该模拟使请求不是您要测试的类的依赖项。看看这个nock,一个 HTTP 模拟和期望库

于 2013-04-26T07:26:43.647 回答
0

createConnection在实例化TestClass.

TestClass.prototype.createConnection = function() {
    console.log("Called redefined createConnection");
}
于 2013-04-25T05:51:41.560 回答