我遇到了ES6 Promise和一些mocha / chai测试的奇怪行为。
考虑以下返回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
你有什么线索来解释这个吗?
如果它有帮助,这是mocha调用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
Bootstrap
答案 0 :(得分: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);
...