chai-as-promised在TypeScript Mocha测试中未按预期失败的问题
解决chai-as-promised在Mocha+TypeScript测试中的问题
你遇到的问题有两个核心原因:未注册chai-as-promised插件,以及未让Mocha等待断言Promise完成,最后还有对API的误解导致的TypeError。
问题1:所有测试"假通过"的原因
你已经导入了chaiAsPromised,但没有调用chai.use(chaiAsPromised)启用插件。这导致expect(...).to.eventually这条断言链根本不生效——你的测试实际没执行任何有效的Promise断言,Mocha看到测试函数同步执行完毕,直接标记为通过,完全没等待getRedColor的Promise结果。
同时,即使插件注册成功,你也没有把chai-as-promised返回的断言Promise返回给Mocha。Mocha只有在收到测试函数返回的Promise时,才会等待它resolve或reject来判断测试结果;如果不返回,Mocha会立即结束测试。
问题2:TypeError的原因
你错误地把eventually当成了Promise对象的方法,实际上它是chai-as-promised给expect断言链添加的扩展。正确的写法是对expect(promise)调用eventually,而不是直接在Promise上调用to.eventually。
修正后的完整测试代码
import * as chai from 'chai'; import { expect } from 'chai'; import 'mocha'; import chaiAsPromised from 'chai-as-promised'; import { getRedColor } from '../src/index'; import { describe } from 'mocha'; // 必须注册chai-as-promised插件,启用扩展断言 chai.use(chaiAsPromised); describe('Testing failing promises with async/await', () => { // 原async/await测试可保留,此处略 }); describe('Testing failing promises chai-as-promised', () => { it('should pass on red', () => { // 返回断言Promise,让Mocha等待结果 return expect(getRedColor('red')).to.eventually.equal('red'); }); it('should throw on blue', () => { return expect(getRedColor('blue')).to.be.rejectedWith('You picked blue, should be red'); }); // 预期失败:red会resolve,断言rejected会触发失败 it('should fail expecting rejection on red', () => { return expect(getRedColor('red')).to.be.rejected; }); // 预期失败:blue会reject,断言等于blue会触发失败 it('should fail resulting in blue', () => { return expect(getRedColor('blue')).to.eventually.eql('blue'); }); });
关键修正点总结
- 注册插件:必须添加
chai.use(chaiAsPromised),让eventually、rejectedWith等扩展断言生效。 - 返回断言Promise:每个chai-as-promised测试都要
return expect(promise).to.eventually...,让Mocha等待断言结果。 - 正确使用API:
eventually是chai断言链的一部分,只能通过expect(promise)调用,不能直接绑定在Promise对象上。
内容的提问来源于stack exchange,提问作者stwissel
相关产品推荐
相关产品推荐

