开玩笑 - 测试成功,即使它不应该成功

Jest - Test is successful even though it should not be

我已经简化了我的脚本,以便您轻松了解正在发生的事情。我有一个等待对象准备就绪的测试,然后再检查数组是否包含值。

const list = ['A', 'B', 'C'];
describe('check array', (done) => {
  it('should not contain D', () => {
    const monitor = new Monitor();

    monitor.ready().then(() => {
      expect(list.indexOf('D')).toEqual(1);

      done();
    });
  });
});

如您所见,D 不是 list 的元素(因此 indexOf 应该 return -1),但是这个测试仍然通过。我试过 toEqualtoBe 都没有成功。我想知道这是否与我正在等待 Promise 首先解决的事实有关?谢谢!

您需要 await 您的 monitor.ready(),像这样:

const list = ['A', 'B', 'C'];

describe('check array', (done) => {
  // made function async
  it('should not contain D', async () => {
    const monitor = new Monitor();

    // wait until this call finished before continuing
    await monitor.ready();
    
    expect(list.indexOf('D')).toEqual(1);

    // not sure where this is from or what it's for
    // I assume it's defined somewhere else in your code
    done(); 
  });
});

没有执行 async/await,测试完成时没有失败的断言或 Jest 解释为通过测试的错误,因为 .then(() => {...}) 中的代码没有运行 直到测试被标记为成功之后