简体   繁体   中英

Jest Axios test is passing when it shouldn't

I am writing a script (see below) to make sure that an axios function throws an error when it receives a certain status code. I found out, however, that even when I make this test fail, Jest still says that the test passes, even though it returns an error in the console (see below). Why is Jest saying this test has passed when it actually failed? Does it have something to do with me trying to expect an error, so even if the test fails, jest still receives an error (that the test failed) and thinks this means that I got what I expected? Thanks.

在此处输入图片说明

foo.test.js:

import axios from 'axios';

jest.mock('axios', () => ({
  get: jest.fn(() => Promise.resolve({ data: 'payload' })),
}));

const getData = async (url) => {
  const response = await axios.get(url);
  if (response.status !== 200) {
    return response.text().then((error) => {
      throw new Error(error.message);
    });
  } else {
    return response.data;
  }
};

test('testing that an error is thrown', async () => {
  axios.get.mockImplementation(() =>
    Promise.resolve({
      data: {data: 'payload'},
      status: 400,
      text: () => Promise.resolve(JSON.stringify({message: 'This is an error.'})),
    })
  );

  const expectedError = async () => {
    await getData('sampleUrl');
  };

  // The error should return 'This is an error.' and instead
  // is expecting 'foo', so this test should fail.
  expect(expectedError()).rejects.toThrowError('foo');
});

You need two changes to get the test to fail as expected.

  • Don't stringify the resolved value from text
  • await the expect that uses rejects

Here is an updated version that fails as expected:

import axios from 'axios';

jest.mock('axios', () => ({
  get: jest.fn(() => Promise.resolve({ data: 'payload' })),
}));

const getData = async (url) => {
  const response = await axios.get(url);
  if (response.status !== 200) {
    return response.text().then((error) => {
      throw new Error(error.message);
    });
  } else {
    return response.data;
  }
};

test('testing that an error is thrown', async () => {
  axios.get.mockImplementation(() =>
    Promise.resolve({
      data: {data: 'payload'},
      status: 400,
      text: () => Promise.resolve({message: 'This is an error.'}),  // <= don't stringify
    })
  );

  const expectedError = async () => {
    await getData('sampleUrl');
  };

  await expect(expectedError()).rejects.toThrowError('foo');  // <= await
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM