function foo() {
throw new Error('an error from (foo)');
}我想检查错误是否包含文本(foo),我尝试:
expect(() => foo()).toThrow(expect.stringContaining('(foo)'))但是它失败了,并且不像预期的那样工作:
● test › checks error containing text
expect(received).toThrowError(expected)
Expected asymmetric matcher: StringContaining "(foo)"
Received name: "Error"
Received message: "an error from (foo)"
1 | function foo() {
> 2 | throw new Error('an error from (foo)');
| ^虽然我可以找到一种使用regex的方法,比如:
expect(() => foo()).toThrowError(/[(]foo[)]/)但这需要我逃避一些特殊的角色,这不是我想要的。
为什么在这种情况下不支持expect.stringContaining?还是我错过了什么?
一个用于尝试的小演示:https://github.com/freewind-demos/typescript-jest-expect-throw-error-containing-text-demo
发布于 2020-10-09 07:28:24
toThrow不接受比赛。每个文献资料的可选错误参数有四个选项:
您可以提供一个可选的参数来测试抛出特定错误:
在您的情况下,您可以使用以下两种方法:
new RegExp;或https://stackoverflow.com/questions/64275525
复制相似问题