How to add custom message to Jest expect?

前端 未结 8 1213
鱼传尺愫
鱼传尺愫 2021-02-03 17:35

Image following test case:

it(\'valid emails checks\', () => {
  [\'abc@y.com\', \'a@b.nz\'/*, ...*/].map(mail => {
    expect(isValid(mail)).toBe(true);
          


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 18:08

    Although it's not a general solution, for the common case of wanting a custom exception message to distinguish items in a loop, you can instead use Jest's test.each.

    For example, your sample code:

    it('valid emails checks', () => {
      ['abc@y.com', 'a@b.nz'/*, ...*/].map(mail => {
        expect(isValid(mail)).toBe(true);
      });
    });
    

    Could instead become

    test.each(
        ['abc@y.com', 'a@b.nz'/*, ...*/],
        'checks that email %s is valid',
        mail => {
            expect(isValid(mail)).toBe(true);
        }
    );
    

提交回复
热议问题