Тест Jest Axios проходит, когда не должен - PullRequest
1 голос
/ 23 апреля 2019

Я пишу скрипт (см. Ниже), чтобы убедиться, что функция axios выдает ошибку при получении определенного кода состояния.Однако я обнаружил, что даже когда я провалю этот тест, Jest все равно скажет, что тест пройден, даже если он возвращает ошибку в консоли (см. Ниже).Почему Джест говорит, что этот тест прошел, а на самом деле не прошел?Имеет ли это какое-то отношение ко мне, пытаясь ожидать ошибку, поэтому, даже если тест не пройден, Jest все равно получает ошибку (что тест не пройден) и думает, что это означает, что я получил то, что ожидал?Спасибо.

enter image description here

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');
});

1 Ответ

1 голос
/ 23 апреля 2019

Вам нужно два изменения, чтобы тест не прошел, как ожидалось.

  • Не переводить разрешенное значение из text
  • await expect, который использует rejects

Вот обновленная версия, которая не работает, как ожидалось:

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
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...