How to add custom message to Jest expect?

前端 未结 8 1203
鱼传尺愫
鱼传尺愫 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);
        }
    );
    
    0 讨论(0)
  • 2021-02-03 18:11

    You can use try-catch:

    try {
        expect(methodThatReturnsBoolean(inputValue)).toBeTruthy();
    }
    catch (e) {
        throw new Error(`Something went wrong with value ${JSON.stringify(inputValue)}`, e);
    }
    
    0 讨论(0)
提交回复
热议问题