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

时间:2015-04-13 07:45:05

标签: node.js jasmine-node

为什么以下代码因超时而失败?它看起来像'应该'抛出一个错误,并且完成()永远不会被调用?如何编写此测试以使其正确失败而不是让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();
      });
  });
});

控制台输出是:

c:> jasmine-node spec \

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

2 个答案:

答案 0 :(得分:4)

使用.then()且仅使用done()

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

使用.then()done.fail()

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

使用Bluebird协同程序

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

使用async / await

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

async / await.catch()

一起使用
it('should work', (done) => {
  (async () => {
    let num = await Promise.resolve(3);
    // your assertions here
    done();
  })().catch(done.fail);
});

其他选项

您明确询问了jasmine-node以及上述示例的内容,但也有其他模块可让您直接从测试中返回承诺,而不是调用done()和{{1 } - 见:

答案 1 :(得分:2)

如果您想在Promises套件中使用Mocha,则必须return而不是使用done()回调,例如:

describe('test', function () {
  it('should work', function () {
    return Promise.resolve(3)
      .then(function (num) {
        num.should.equal(4);
      });
  });
});

使用chai-as-promised模块编写更简洁的方法:

describe('test', function () {
  it('should work', function () {
    return Promise.resolve(3).should.eventually.equal(4);
  });
});

请确保正确使用并告诉chai使用它:

var Promise = require('bluebird');
var chai = require('chai');
var should = chai.should();
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);