怪异的断言与摩卡/柴和ES6诺言
我面对一个奇怪的行为与ES6承诺和一些摩卡/柴testing。 考虑下面的foo()
函数返回一个promise,我想testing两件事情:
- 它返回一个承诺(所以,一个对象)
- 它会抛出一个exception(所以,一个对象)的失败。
问题是,下面的testingexpect(..).to.be.an('object')
在这两种情况下失败,但types是 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
柴使用type-detect
a/an
,这是聪明的(取决于你如何看待它)在键入对象。
例如:
var type = require('type-detect'); var promise = new Promise(() => {}); console.log( type(promise) ) // 'promise'
所以这会让你的testing通过:
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); ...