簡體   English   中英

Jest Axios 測試在不應該通過的時候通過了

[英]Jest Axios test is passing when it shouldn't

我正在編寫一個腳本(見下文)以確保 axios 函數在收到特定狀態代碼時拋出錯誤。 然而,我發現即使我使這個測試失敗,Jest 仍然說測試通過,即使它在控制台中返回一個錯誤(見下文)。 為什么 Jest 說這個測試通過了,而實際上它失敗了? 它是否與我試圖預期錯誤有關,因此即使測試失敗,jest 仍然收到錯誤(測試失敗)並認為這意味着我得到了預期的結果? 謝謝。

在此處輸入圖片說明

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

您需要進行兩次更改才能使測試按預期失敗。

  • 不要將text的解析值字符串化
  • await使用rejectsexpect

這是一個按預期失敗的更新版本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM