使用 Chai 和 Sinon 测试承诺的服务

testing promised service with Chai and Sinon

我坚持在 Chai 和 Sinon 中测试 promies。通常我得到的服务是 xhr 请求的包装器,它 returns 承诺。我试过这样测试它:

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

我的笔记:

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

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

这里有各种挑战:

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

试试这个:

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