使用catch in promise进行断言超过超时时间

Making assertions with catch in promises exceeds timeout

本文关键字:超时 时间 断言 catch in promise 使用      更新时间:2023-09-26

我想在promise链的catch块中进行断言,但它达到了超时。断言在then块中起作用,但在catch块中,似乎从未达到done()。它被压制了吗?有没有更好的方法来测试拒绝承诺的情况?

import assert from 'assert';
import { apicall } from '../lib/remoteapi';
describe('API calls', function () {
  it('should test remote api calls', function (done) {
    apicall([])
      .then((data) => {
        assert.equal(data.items.length, 2); // this works fine
        done();
      })
      .catch((e) => {
        console.log('e', e);
        assert.equal(e, 'empty array'); // ? 
        done(); // not reached?
      });
  });
});

拒绝承诺

apicall(channelIds) {
  if(channelIds.length === 0) return Promise.reject('empty array');
  ...        
}

我得到这个错误:

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

如果这是摩卡,并且您正在使用Promises,请不要使用回调功能;正如你所发现的那样,这会让事情变得非常尴尬。相反,摩卡让你在测试中返回承诺。被拒绝的Promise意味着测试失败,成功的Promise则意味着测试成功。失败的断言会导致代码抛出异常,这将自动使Promise失败,这通常是您想要的。简而言之:

describe('API calls', function () {
  it('should test remote api calls', function () {
    return apicall([])
      .then((data) => {
        assert.equal(data.items.length, 2);
      });
  });
});