在Jest中,我怎样才能使测试失败?

kYu*_*uZz 17 javascript jestjs

我知道我可以从测试中抛出错误,但我想知道是否有像fail()Jasmine提供的全局方法?

Bea*_*ith 17

复制/面试失败:

it('This test will fail', done => {
  done.fail(new Error('This is the error'))
})
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言,这应该是公认的答案。对于同步测试,您只需使用`fail(new Error('What the fork?'));` (3认同)
  • 不适用于(最新)Jest -> 只需坚持接受的答案或使用“抛出新错误('What the fork?')” (3认同)

Cri*_*san 15

你可以通过抛出错误来做到这一点.例如:

test('Obi-Wan Kenobi', () => {
  throw new Error('I have failed you, Anakin')
})
Run Code Online (Sandbox Code Playgroud)

  • OP 说他们知道抛出错误......这并没有按要求提供新的解决方案。(尽管其他方面都很好。) (5认同)

Ras*_*ash 11

以下是某些答案不起作用的某些情况。在 的世界中async-await,像这样的 try-catch 逻辑是很常见的。

try {
  await someOperation();
} catch (error) {
  expect(error.message).toBe('something');
}
Run Code Online (Sandbox Code Playgroud)

现在想象一下,如果someOperation()以某种方式通过了,但您预计它会失败,那么该测试仍然会通过,因为它从未进入 catch 块。所以我们想要的是确保如果 someOperation 没有抛出错误,测试就会失败。

现在让我们看看哪些解决方案有效,哪些无效。

接受的答案在这里不起作用,因为投掷会再次被抓住。

try {
  await someOperation();
  throw new Error('I have failed you, Anakin');
} catch (error) {
  console.log('It came here, and so will pass!');
}
Run Code Online (Sandbox Code Playgroud)

true === false 的答案也不起作用,因为断言也会抛出类似上面的错误,该错误将被捕获。

try {
  await someOperation();
  expect(true).toBe(false); // This throws an error which will be catched.
} catch (error) {
  console.log('It came here, and so will pass!');
}
Run Code Online (Sandbox Code Playgroud)

对于这种情况,一种有效的解决方案(如@WhatWouldBeCool 的回答所示)如下。现在它明确地未通过测试。

try {
  await someOperation();
  fail('It should not have come here!')
} catch (error) {
  console.log('It never came here!');
}
Run Code Online (Sandbox Code Playgroud)


Wha*_*ool 10

Jest实际上使用Jasmine,因此您可以fail像以前一样使用。

样品通话:

fail('it should not reach here');
Run Code Online (Sandbox Code Playgroud)

这是Jest的TypeScript声明文件中的定义:

declare function fail(error?: any): never;
Run Code Online (Sandbox Code Playgroud)

  • 我收到错误“未定义失败”。似乎是一个已知问题:https://github.com/facebook/jest/issues/11698 (21认同)
  • 不应该使用 Jasmine 全局变量,因为它将在 jest 的未来版本中删除,更喜欢抛出错误 `throw new Error()` 或 did.fail 方法。https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/no-jasmine-globals.md (11认同)