How I can test in jest line with throw e?

后端 未结 2 456
青春惊慌失措
青春惊慌失措 2021-01-27 02:38

How I can test in jest error case? This is what I do: I don\'t know if exist a method how to test this.

it (\'the fetch fails and throw an error\', async () =         


        
相关标签:
2条回答
  • 2021-01-27 02:53

    You can do it in the following way:

    async function throws () {
      throw new Error('error')
    }
    
    test('promise throws', async () => {
      await expect(throws()).rejects.toThrow()
    })
    
    test('the fetch fails with an error', async () => {
      await expect(throws()).rejects.toThrow('error');
    });
    
    test('the fetch fails with an error', () => {
      return expect(throws()).rejects.toMatch('error');
    });
    

    Read more docs.

    0 讨论(0)
  • 2021-01-27 02:57

    expect.assertions to the rescue

    it ('the fetch fails and throw an error', async () => {
      expect.assertions(1);
      let response = {
        status: 400,
        body: {
          base : "RON",
          date: "2019-08-01",
          rates: {"error": 'error'}
        }
      };
      fetch.mockReject(response)
      try {
        await fetchData();
      } catch (e) {
        expect(e).toEqual(response);
      }
    });
    

    Test will fail once no exception is thrown. It has advantages over expect().toThrown:

    1. you don't have to return Promise in your it() to make it work
    2. it's easier to assert several related exceptions or sequential actions failed
    3. it's easier to run partial matching over error caught(say with expect(e).toMatchObject({}) to skip some data you don't care about in current test case)

    As for disadvantages - you have to update number manually after adding new assertions

    0 讨论(0)
提交回复
热议问题