承诺不会在单元测试中解决

时间:2018-05-21 05:33:47

标签: javascript unit-testing typescript promise

承诺在单元测试中无法解决。

it('should break', function(done){
     const promise =  Promise.resolve([1, 2, 3, 4 , 5]); 
     promise.then(function(){
         expect(true).to.be.false;
         done();
     });
});

我也试过这个。 (这实际上适用于我创建的单独的新示例项目,但这不适用于我的实际项目,所以这很奇怪

从'chai'导入{expect};

describe('Hello function',function(){

it('should return hello world', function () {
    const promise = Promise.resolve(1);
    return promise.then(function () {
        expect(true).to.be.false;
    });
});

});

背景     “karma-mocha”:“^ 1.3.0”,     “karma-webpack”:“^ 2.0.1”,     “karma-chai”:“^ 0.1.0”,     “karma-chrome-launcher”:“^ 2.2.0”,     “打字稿”:“~2.3.4”,     “tslint-loader”:“^ 3.3.0”,

在karma.config.js

框架:['mocha','chai'],  浏览器:['ChromeHeadless'],

我收到错误消息

✖ should break
  HeadlessChrome 0.0.0 (Mac OS X 10.12.6)
Error: Timeout of 9999ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

2 个答案:

答案 0 :(得分:0)

有两种方法可以使用mocha进行异步测试。使用done()或返回承诺。

因为你正在使用承诺,所以只返回承诺是最有意义的。此示例删除done并返回promise。

it('should break', function(){
  const promise =  Promise.resolve([1, 2, 3, 4 , 5]); 
  return promise.then(function(){
    expect(true).to.be.false;
  });
});

重写为async / await + arrow功能:

it('should break', async () => {
  await [1, 2, 3, 4 , 5];
  expect(true).to.be.false;
});

使用done() 是可能的,但您不应该混合返回的承诺并调用done()

答案 1 :(得分:-1)

你必须在断言后返回承诺并调用done()。

it('should break', function(done){
 const promise =  Promise.resolve([1, 2, 3, 4 , 5]); 
 return promise.then(function(){
     expect(true).to.be.false;
     done();
 });
});
相关问题