2015-06-07 54 views
2

我正面临着通过运行mocha来通过测试的麻烦,这似乎已经过去了。摩卡测试蓝鸟支持的节点风格回调

测试:

describe('.get()',function() { 

    it('should be called once',function() { 
     // => Need to spy on this 
     var callback = function(err,data) { 
      console.log('I am called'); 
      if (err) { 
       console.log('I am logging the error '+err); 
      } else { 
       console.log('I am logging the data '+data); 
      } 
     } 

     agentMock._response = {body:'something',headers:'headers'}; 

     // => Start Spying 
     var spy = sinon.spy(callback); 
     sinon.spy(agentMock,'get'); 

     baseRequest.get(spy); // refer (a) below 

     expect(agentMock.get).to.have.been.calledOnce; 
     expect(spy).to.have.been.calledOnce; 
     expect(spy).to.have.been.calledWith(null,'data'); 
    }); 
}); 

我想测试callback是否被称为与否。因此,我登录了回调的主体,标准输出也表明它正在被调用。

标准输出:

.get() 
    1) should be called once 
I am called 
I am logging the data something 


    0 passing (15ms) 
    1 failing 

    1) .get() should be called once: 
    AssertionError: expected spy to have been called exactly once, but it was called 0 times 

详情:

(一)baseRequest.get返回数据为bluebird承诺。这可以通过在nodeback.get本身或通过在.get呼叫之后链接.then来使用。

BaseRequest.prototype.get = function(callback) { 
    // inner details 

    return invokeandPromisify(request,callback); 
} 

function invokeandPromisify(request, callback) { 
    return new Promise(function(resolve,reject) { 
    // Invoke the request 
    request.end(function(err,result) { 

     // Return the results as a promise 
     if (err || result.error) { 
      reject(err || result.error); 
     } else { 
      resolve(result); 
     } 
    }); 
    }).nodeify(callback); // to have a node style callback 
} 

是否发生,因为回调上,我想间谍传递给不同的功能(invokeandPromisify这里)和间谍丢了?我只是在解释这一点。

问候。

回答

2

由于baseRequest#get返回一个承诺,我会做出断言的承诺得到解决之后。

参见下例:

it('should be called once',function(done) { 
    // => Need to spy on this 
    var callback = function(err,data) { 
     console.log('I am called'); 
     if (err) { 
      console.log('I am logging the error '+err); 
     } else { 
      console.log('I am logging the data '+data); 
     } 
    } 

    agentMock._response = {body:'something',headers:'headers'}; 

    // => Start Spying 
    var spy = sinon.spy(callback); 
    sinon.spy(agentMock,'get'); 

    baseRequest.get(spy).finally(function() { 
     expect(agentMock.get).to.have.been.calledOnce; 
     expect(spy).to.have.been.calledOnce; 
     expect(spy).to.have.been.calledWith(null,'data'); 
     done(); 
    }); 

}); 
+0

谢谢,救了我的一天!你能详细说一下这里有什么问题,因为我已经通过设置'agentMock._response'的值来设置响应了。 – darxtrix

+0

之后不是同步测试吗?我没有得到它。 – darxtrix

+1

承诺是异步的,所以你的测试也必须是异步的。我使用了'#finally'来确保当promise被解析时断言,然后调用'done()'来表示异步测试的结束。 – JME

1

通过添加完成,您的测试应该设置为异步。然后在回调funtion调用来完成()

请检查http://mochajs.org/#asynchronous-code

+0

'agentMock._response = {体: '某物',标头: '报头'};'立即设置响应。那么,现在是异步吗? – darxtrix

+0

好的,我应该叫它'done'。 – darxtrix