【问题标题】:Cannot see post-axios call rendered component contents看不到 axios 调用后渲染的组件内容
【发布时间】:2023-03-15 19:05:02
【问题描述】:

我正在使用 useEffect 在我的组件的初始渲染中进行 axios 调用,但是在我返回包含该调用内容的 200 响应后,我无法实际测试我的组件的内容...

Component.jsx

const MyComp = () => {
    const [data, setData] = useState(null);

    useEffect(() => {
        axios.get('/my-url').then(data => setData(data.data));
    }, []);

    return (
        <div>
            { data && <div data-testid="data">{data}</div> }
        </div>
    );
}

Component.spec.js

test('should render data when loaded', async () => {
    mockAxios.onGet("/my-url").reply(200, { data: 'hello' });

    rendered = render(<MyComp />);

    await waitFor(() => rendered.getByTestId("data"));

    expect(rendered.getByTestId("data")).toBeTruthy();
    expect(rendered.getByTestId("data").textContent).toBe("hello");
});

此测试运行后,我收到错误:

Unable to find an element by: [data-testid="data"]

【问题讨论】:

  • 你在用react-testing-library吗?
  • @slideshowp2 确实是我

标签: javascript reactjs unit-testing axios react-testing-library


【解决方案1】:

axios.get() 返回AxiosResponse,其接口如下:

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

您为axios-mock-adapter 提供模拟数据{ data: 'hello' }。您应该通过res.data.data 属性获取hello 字符串。

例如

Component.jsx:

import axios from 'axios';
import React from 'react';
import { useEffect, useState } from 'react';

export const MyComp = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    axios.get('/my-url').then((res) => {
      setData(res.data.data);
    });
  }, []);

  return <div>{data && <div data-testid="data">{data}</div>}</div>;
};

Component.test.jsx:

import { MyComp } from './Component';
import MockAdapter from 'axios-mock-adapter';
import axios from 'axios';
import React from 'react';
import { render, waitFor } from '@testing-library/react';

const mock = new MockAdapter(axios);

describe('68064134', () => {
  it('should pass', async () => {
    mock.onGet('/my-url').reply(200, { data: 'hello' });

    const rendered = render(<MyComp />);

    await waitFor(() => rendered.getByTestId('data'));

    expect(rendered.getByTestId('data')).toBeTruthy();
    expect(rendered.getByTestId('data').textContent).toBe('hello');
  });
});

测试结果:

PASS  examples/68064134/Component.test.tsx (12.285 s)
  68064134
    ✓ should pass (28 ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 Component.tsx |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.264 s

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2021-08-28
    • 2018-06-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多