【问题标题】:Weird failed assertion with mocha/chai and ES6 Promisemocha/chai 和 ES6 Promise 的奇怪断言失败
【发布时间】:2015-12-23 15:14:35
【问题描述】:

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

  • 它返回一个承诺(因此,一个对象)
  • 它在失败时抛出一个异常(因此,一个对象)。

问题是,以下测试expect(..).to.be.an('object') 在这两种情况下都失败了,但类型 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 调用的结果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

【问题讨论】:

    标签: node.js mocha.js chai es6-promise


    【解决方案1】:

    Chai 将type-detect 用于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);
    ...
    

    【讨论】:

    • 确实它现在工作得更好了!可惜它没有像“promise is an object”这样的继承系统......感谢您的回答!
    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2017-03-04
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多