在mocha中,断言函数中的“断言”导致超时而非失败

时间:2016-09-09 07:09:30

标签: javascript testing mocha

我有以下测试:

it ('clears the many cache when a new document is inserted', () => {

return new Promise(async(resolve) => {
    const entity = new Entity(connector, collectionName);
    entity.insert({_id: '2'});
    result = await entity.findManyCached();

    // this assert does not fail the test, but makes the case time out
    assert.deepEqual(result, [{_id: 1}]);
  })
})

如何收集失败的断言而不是超时的结果?

1 个答案:

答案 0 :(得分:0)

我认为发生的事情是因为使promise async的执行函数成功,你将得到相当于:

return new Promise(outerResolve => {
  return new Promise(innerResolve => {
    ...
    assert.deepEqual(...);
  })
})

assert引发的任何异常都被内部承诺吞噬,外部承诺永远不会被解决被拒绝,因此超时。

独立演示:

let p = new Promise(outerResolve => {
  console.log('outer promise');
  return new Promise(innerResolve => {
    console.log('inner promise');
    throw Error('foo');
  })
})

// This doesn't log anything:    
p.then (x => console.log('resolved'))
 .catch(e => console.log('rejected'));

这是一种解决方法:

it ('clears the many cache when a new document is inserted', async () => {
  const entity = new Entity(connector, collectionName);
  entity.insert({_id: '2'});
  let result = await entity.findManyCached();

  // this assert does not fail the test, but makes the case time out
  assert.deepEqual(result, [{_id: 1}]);
})