首页 文章

与mocha / chai和ES6 Promise断言的奇怪失败

提问于
浏览
1

我遇到了ES6 Promise和一些mocha / chai测试的奇怪行为 . 考虑以下 foo() 函数返回一个promise,我想测试两件事:

  • 它返回一个promise(所以,一个对象)

  • 它在失败时抛出异常(以及对象) .

问题是,在测试 expect(..).to.be.an('object') 两种情况下都失败了,但类型 is object (用 typeof 检查) .

这是我的代码:

var chai = require('chai');
var expect = chai.expect;

var foo = function (a, b) {
  return new Promise(function(resolve, reject) {
    if (a < b) {
      resolve();
    }
    else {
      throw new Error('failed');
    }
  });
}

describe('foo function', function () {
  it('should return a promise', function () {
    var call = foo();

    //typeof call: object
    expect(call).to.be.defined; //pass
    expect(call).to.be.an('object'); //fail
    expect(call.then).to.be.a('function'); //pass
  });

  it('should throw an exception on failure', function () {
    return foo().catch(function (e) {

      //typeof e: object
      expect(e).to.be.defined; //pass
      expect(e).to.be.an('object'); //fail
    });
  })
});

你有什么线索来解释这个吗?

如果它可以帮助,这里是摩卡调用的结果 mocha test.js

foo function
  1) should return a promise
  2) should throw an exception on failure


0 passing (20ms)
2 failing

1) foo function should return a promise:
   AssertionError: expected {} to be an object
    at Context.<anonymous> (test.js:34:24)

2) foo function should throw an exception on failure:
   AssertionError: expected [Error: failed] to be an object
    at test.js:42:23

1 回答

  • 1

    Chai使用type-detect for a/an ,这在输入对象时很聪明(取决于你如何看待它) .

    例如:

    var type    = require('type-detect');
    var promise = new Promise(() => {});
    
    console.log( type(promise) ) // 'promise'
    

    所以这将使你的测试通过:

    expect(call).to.be.a('promise');
    ...
    expect(e).to.be.an('error');
    ...
    

    要么是,要么使用.instanceOf()

    expect(call).to.be.an.instanceOf(Object);
    ...
    expect(e).to.be.an.instanceOf(Error);
    ...
    

相关问题