【问题标题】:jest toEqual not working with exception matching开玩笑 toEqual 不适用于异常匹配
【发布时间】:2019-07-08 06:44:26
【问题描述】:

我是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 |

如何检查?

【问题讨论】:

    标签: node.js testing jestjs nestjs


    【解决方案1】:

    代替toEqual 试试toThrow

    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

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2015-07-15
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多