gpt4 book ai didi

javascript - Mocha 测试 Bluebird 驱动的 Node 样式回调

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:16 24 4
gpt4 key购买 nike

我遇到了通过运行似乎通过的 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 是否被调用。因此,我登录了回调主体,stdout 也表明它正在被调用。

标准输出:

  .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

详细信息:

(a) baseRequest.get 将数据作为 bluebird promise 返回。这可以通过将 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)并且监视是丢失的 ?我只是在解释这个。

问候。

最佳答案

因为 baseRequest#get 返回一个 promise ,我会在 promise 被解决后做出断言。

请看下面的例子:

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();
});

});

关于javascript - Mocha 测试 Bluebird 驱动的 Node 样式回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com