看不到 post-axios 调用呈现的组件内容

Cannot see post-axios call rendered component contents

我在我的组件的初始渲染中使用 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"]

axios.get() returns 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