Mocha和Chai没有答应

Mocha and Chai fail insde a promise

本文关键字:答应 Chai Mocha      更新时间:2023-09-26

我无法让Chai expect在这个简单的例子中工作:Mocha的done函数似乎从未被调用,断言也被忽略:

import chai, {expect} from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
import 'isomorphic-fetch';
describe('Mocha and Chai', () => {
  it('tests chai expect inside a promise', (done) => {
    fetch('http://google.com').then(() => {
      const actual = 'test';
      const expected = 'expected';
      console.log(`'${actual}'' equals to '${expected}'?`, actual === expected);
      expect(actual).to.be.equals(expected);
      expect(actual).to.eventually.be.equals(expected);
      done();
    });
  });
});

请注意,我已经尝试了这两种方法,使用和不使用chai-as-promisedeventually

这是相关的输出:

> mocha tools/testSetup.js "src/**/*.spec.js" --reporter progress
'test'' equals to 'expected'? false
  1) Mocha and Chai tests chai expect inside a promise:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

正如你所看到的,承诺正在发挥作用,我得到了控制台输出。但是expect()调用work和done()调用都不执行任何操作。

我不确定它是否相关,但我使用的是isomorphic-fetch和建议的es6-promise

我发现了问题。实际上并不需要done回调。Mocha理解如果您返回it()块内的承诺:

it('tests chai expect inside a promise', () => {
   return fetch('http://google.com').then(() => {
     const actual = 'test';
     const expected = 'expected';
     console.log(`'${actual}'' equals to '${expected}'?`, actual === expected);
     expect(actual).to.be.equals(expected);
     expect(actual).to.eventually.be.equals(expected);        
   });
});