简体   繁体   English

摩卡和柴失败了诺言

[英]Mocha and Chai fail insde a promise

I can't make Chai expect work in this simple example: Mocha's done function never seems to get called and assertions are simply ignored: 在这个简单的示例中,我无法让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();
    });
  });
});

Note that I have tried both, with and without chai-as-promised 's eventually . 请注意,我eventually都尝试了带或不带chai-as-promised

This is the relevant output: 这是相关的输出:

> 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.

As you can see, the promise is working, I get my console output. 如您所见,promise在起作用,我得到了控制台输出。 But neither the expect() calls work nor the done() call does anything. 但是Expect expect()调用不起作用, done()调用也不起作用。

I am not sure if it's relevant, but I'm using isomorphic-fetch and the suggested es6-promise . 我不确定是否相关,但是我正在使用isomorphic-fetch和建议的es6-promise

I found the problem. 我发现了问题。 The done callback is not actually needed. 实际不需要done回调。 Mocha understand the scenario if you return the promise inside the it() block: 如果您在it()块中返回 promise, 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);        
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM