摩卡和柴未能兑现承诺

时间:2016-07-25 20:21:48

标签: javascript mocha chai es6-promise isomorphic-fetch-api

我不能让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-promised的{​​{1}},我都尝试过这两种情况。

这是相关的输出:

eventually

正如您所看到的,承诺正在发挥作用,我得到了我的控制台输出。但> 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()调用无效。

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

1 个答案:

答案 0 :(得分:1)

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

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);        
   });
});