How I can test in jest line with throw e?

后端 未结 2 455
青春惊慌失措
青春惊慌失措 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: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

提交回复
热议问题