我在ES6 Promise和一些mocha/chai测试中遇到了一个奇怪的行为。考虑到以下返回promise的foo()
函数,我想测试两件事:
- 它返回一个promise(以及一个对象)
- 它在失败时抛出一个异常(因此也抛出一个对象)
问题是,以下测试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 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
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);
...