我如何正确地使 jasmine-node 中的异步单元测试失败

use*_*889 3 node.js jasmine-node

为什么以下代码会因超时而失败?看起来“应该”抛出错误并且 done() 永远不会被调用?如何编写此测试以使其正确失败而不是让 jasmine 报告超时?

var Promise = require('bluebird');
var should = require('chai').should();
describe('test', function () {
  it('should work', function (done) {
    Promise.resolve(3)
      .then(function (num) {
        num.should.equal(4);
        done();
      });
  });
});
Run Code Online (Sandbox Code Playgroud)

控制台输出是:

c:>茉莉花节点规范\

未处理的拒绝 AssertionError:预期 3 等于 4 ...失败:1)测试应该工作消息:超时:等待规范完成 5000 毫秒后超时

rsp*_*rsp 5

使用.then()且仅done()

it('should work', (done) => {
  Promise.resolve(3).then((num) => {
    // your assertions here
  }).catch((err) => {
    expect(err).toBeFalsy();
  }).then(done);
});
Run Code Online (Sandbox Code Playgroud)

使用.then()done.fail()

it('should work', (done) => {
  Promise.resolve(3).then((num) => {
    // your assertions here
  }).then(done).catch(done.fail);
});
Run Code Online (Sandbox Code Playgroud)

使用 Bluebird 协程

it('should work', (done) => {
  Promise.coroutine(function *g() {
    let num = yield Promise.resolve(3);
    // your assertions here
  })().then(done).catch(done.fail);
});
Run Code Online (Sandbox Code Playgroud)

使用async/await

it('should work', async (done) => {
  try {
    let num = await Promise.resolve(3);
    // your assertions here
    done();
  } catch (err) {
    done.fail(err);
  }
});
Run Code Online (Sandbox Code Playgroud)

使用async/await.catch()

it('should work', (done) => {
  (async () => {
    let num = await Promise.resolve(3);
    // your assertions here
    done();
  })().catch(done.fail);
});
Run Code Online (Sandbox Code Playgroud)

其他选项

您专门询问jasmine-node了以上示例的内容,但还有其他模块可让您直接从测试中返回承诺而不是调用done()done.fail()- 请参阅: