node.js - 开 Jest toEqual 不适用于异常匹配

标签 node.js testing jestjs nestjs

我是 jest 的新手,所以我不确定这是否是我的错。所以这是我的测试用例

    it('should throw error if wrong email or phone number is provided', async () => {
      await expect(userService.verifyCredentials('invalidemail@invaliddomain.com', 'sayantan94'))
        .rejects
        .toEqual(new UnauthorizedException('Invalid email or phone number'));
    })

但即使抛出相同的异常,这也会失败。这是输出

FAIL  src/modules/user/user.service.spec.ts (5.156s)
● UserService › verifyCredentials › should throw error if wrong email or phone number is provided

expect(received).toStrictEqual(expected)

Expected value to equal:
  [Error: [object Object]]
Received:
  [Error: [object Object]]

Difference:

Compared values have no visual difference.

  88 |       await expect(userService.verifyCredentials('invalidemail@invaliddomain.com', 'sayantan94'))
  89 |         .rejects
> 90 |         .toEqual(new UnauthorizedException('Invalid email or phone number'));
     |          ^
  91 |     })
  92 |   })
  93 |

我该如何检查?

最佳答案

尝试使用 toThrow 而不是 toEqual

it('should throw error if wrong email or phone number is provided', async () =>  {        
    await expect(userService.verifyCredentials('invalidemail@invaliddomain.com', 'sayantan94'))
    .rejects
    .toThrow('Invalid email or phone number');
});

引用:https://jestjs.io/docs/en/expect.html#rejects

关于node.js - 开 Jest toEqual 不适用于异常匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687031/

相关文章:

javascript - 将具有换行符的文本与另一个字符串匹配

带有 fs.readFile 的 Node.js 无法通过 http 呈现文件内容

node.js - Sails Js 读取上传的文件内容

react-native - 无效或意外的 token ,测试裸 react native 应用程序

javascript - 开 Jest : Share Variables Between Test Files

mocking - 使用 axios 拦截器模拟 axios

javascript - not.toEqual() 返回 true 尽管键值不同

json - NodeJS JSON 应该是全局的,但它是本地的

node.js - npm 已安装,但运行 "sudo apt-get install npm"会出现错误。为什么?

testing - 一个测试Kafka集群性能的框架