开玩笑:如何故意使 Axios 请求失败

问题描述 投票:0回答:1

我正在测试一个下载徽标图像并将其显示在页面上的组件。第一个测试 - 工作正常 - 检查页面加载时图像是否存在。这是一个非常简化的测试版本:

import Logo from 'path-to-logo/logo';
import Response from 'fixtures/logo';

const result = { url: 'https://route-to-image' };

axios.onGet(result.url).reply(200, Response);

test('the logo image exists on the page', async () => {
  render(<Logo />);
  await waitFor(() => expect(screen.queryByAltText(Response.description)).toBeInTheDocument());
});

第二个测试必须检查图像未通过病毒扫描后会发生什么,在这种情况下,API 请求返回 422 状态而不是 200,并且显示占位符图像而不是徽标。这在组件中按预期工作,但是当我将 axios 状态更改为 422 时,测试失败并抛出错误:

axios.onGet(result.url).reply(422,{});

test('the placeholder image exists on the page', async () => {
  render(<Logo />);
  await waitFor(() => expect(screen.queryByAltText('placeholderImage')).toBeInTheDocument());
});

这是第二次测试的结果:

thrown: Object {
  "config": Object {
    "cancelToken": CancelToken {
      "promise": [Promise],
    },
    "credentials": "include",
    "data": undefined,
    "headers": Object {
      "Accept": "application/json",
      "Access-Control-Allow-Credentials": "true",
      "Access-Control-Allow-Headers": "Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept, Authorization, Content-Disposition",
      "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT,DELETE,PATCH",
      "Access-Control-Allow-Origin": "http://localhost",
      "Content-Type": "application/json",
    },
    "maxBodyLength": -1,
    "maxContentLength": -1,
    "method": "get",
    "mode": "cors",
    "responseType": "json",
    "returnWholeResponse": true,
    "timeout": 0,
    "transformRequest": Array [
      [Function transformRequest],
    ],
    "transformResponse": Array [
      [Function transformResponse],
    ],
    "transitional": Object {
      "clarifyTimeoutError": false,
      "forcedJSONParsing": true,
      "silentJSONParsing": true,
    },
    "url": "https://route-to-url",
    "validateStatus": [Function validateStatus],
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
  },
  "data": Object {},
  "headers": undefined,
  "request": Object {
    "responseURL": "https://route-to-image",
  },
  "status": 422,
}

  at _getError (node_modules/jest-circus/build/utils.js:509:18)
      at Array.map (<anonymous>)

那么如何让 Jest 接受错误代码以便显示占位符图像?

javascript reactjs axios jestjs react-testing-library
1个回答
0
投票

您可以使用 try/catch 块让 Jest 接受错误代码。像这样的简单示例(只需使用渲染逻辑更改 catch 块):

test('axios accepts error 422', async () => {
    try {
        await axios.get(result.url);
    } catch (error) {
        expect(error.response.status).toBe(422);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.