How I can test in jest line with throw e?

2020-05-06 17:16发布

问题:

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 () => {
      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);
        expect(await fetchData()).rejects.toThrow(e);
      }
    });

This is the code:

 fetchData = async () => {
    try {
      const response = await fetch('https://api.exo/latest?base=RON');
      const data = await response.json();
      return data;
    } catch (e) {
      throw e;
    }
  };

回答1:

expect.assertions to the rescue

it ('the fetch fails and throw an error', async () => {
  jest.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



回答2:

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.