gpt4 book ai didi

javascript - 与 Chai 和 Sinon 一起测试 promise 的服务

转载 作者:行者123 更新时间:2023-12-03 07:52:03 26 4
gpt4 key购买 nike

我一直在 Chai 和 Sinon 中测试 promies。一般来说,我使用 xhr 请求的包装器获得服务,并且它返回 promise 。我尝试这样测试:

beforeEach(function() {
server = sinon.fakeServer.create();
});

afterEach(function() {
server.restore();
});

describe('task name', function() {
it('should respond with promise error callback', function(done) {

var spy1 = sinon.spy();
var spy2 = sinon.spy();

service.get('/someBadUrl').then(spy1, spy2);

server.respond();
done();

expect(spy2.calledOnce).to.be.true;
expect(sp2.args[0][1].response.to.equal({status: 404, text: 'Not Found'});
});
});

我对此的笔记:

//在expect完成断言后调用spy2
//尝试使用 var timer = sinon.useFakeTimers()timer.tick(510); 没有结果
//尝试使用 chai-as-promised - 不知道如何使用它:-(
//无法安装 sinon-as-promised 仅在我的环境中选择可用的 npm 模块

有什么想法如何修复此代码/测试此服务模块吗?

最佳答案

这里存在各种挑战:

  • 如果 service.get() 是异步的,则需要等待其完成后再检查断言;
  • 由于(建议的)解决方案检查 Promise 处理程序中的断言,因此您必须小心异常。我不会使用 done(),而是选择使用 Mocha 的(我假设您正在使用)内置的 Promise 支持。

试试这个:

it('should respond with promise error callback', function() {
var spy1 = sinon.spy();
var spy2 = sinon.spy();

// Insert the spies as resolve/reject handlers for the `.get()` call,
// and add another .then() to wait for full completion.
var result = service.get('/someBadUrl').then(spy1, spy2).then(function() {
expect(spy2.calledOnce).to.be.true;
expect(spy2.args[0][1].response.to.equal({status: 404, text: 'Not Found'}));
});

// Make the server respond.
server.respond();

// Return the result promise.
return result;
});

关于javascript - 与 Chai 和 Sinon 一起测试 promise 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962647/

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