axios 测试一个使用自定义钩子的组件,该钩子将数据返回到呈现元素

k3fezbri  于 2023-03-29  发布在  iOS
关注(0)|答案(1)|浏览(143)

我目前正在测试一个使用自定义钩子提供的数据的组件,并检查它是否呈现了其中的所有元素。
AgentsContainer.js

import React from 'react';
import { useFetch } from '../../hooks/useFetch.js';
import AgentBox from './AgentBox/AgentBox.js';

function AgentsContainer() {
    const { agents, loading, error } = useFetch(
        'https://valorant-api.com/v1/agents'
    );

    return (
        <section>
            <div>
                {error && <div>Error: {error.message}</div>}

                {loading && <div>Loading...</div>}

                {agents?.map(agent => {
                    return (
                        agent.isPlayableCharacter && (
                            <AgentBox key={agent.uuid} data-testid='agent-card' {...agent} />
                        )
                    );
                })}
            </div>
        </section>
    );
}

export default AgentsContainer;

另外,请注意,如果我删除“agents”变量后面的问号,它会返回一个错误,内容是“TypeError:无法读取未定义的属性(阅读'map')"。
useFetch.js

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

export function useFetch(url) {
    const [agents, setAgents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState();

    useEffect(() => {
        setLoading(true);

        axios
            .get(url)

            .then(({ data: { data } }) => {
                setAgents(data);
            })

            .catch(error => setError(error))

            .finally(() => setLoading(false));
    }, []);

    return { agents, loading, error };
}

AgentsContainer.test.js

import React from 'react';
import { render, screen } from '@testing-library/react';
import AgentsContainer from './AgentsContainer.js';
import agentsMock from '../../mock/mock.js';
import axios from 'axios';

jest.mock('axios');

test('Renders Agents cards', async () => {
    axios.get.mockResolvedValue({
        data: agentsMock,
        loading: true,
        error: 'Something went wrong D:'
    });

    render(<AgentsContainer />);

    const agentsCards = await screen.findAllByTestId('agent-card');

    expect(agentsCards).toHaveLength(3);
});

控制台

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

    Ignored nodes: comments, script, style
    <body>
      <div>
        <section>
          <div />
        </section>
      </div>
    </body>

      16 |      render(<AgentsContainer />);
      17 |
    > 18 |      const agentsCards = await screen.findAllByTestId('agent-card');
         |                                       ^
      19 |
      20 |      expect(agentsCards).toHaveLength(3);
      21 | });

我在测试文件中导入的“mockAgents”只是一个对象数组,它里面只有3个对象,里面有多个数据,我没有把mock放在这里,因为它有太多的数据。但是如果你真的需要它,请告诉我:)

ahy6op9u

ahy6op9u1#

好吧,我找到问题了。
我只是改变了我模拟JSON文件的方式,这就解决了问题。
AgentsContainer.test.js

test('Should render Agents cards', async () => {
    axios.get.mockResolvedValue({
        data: { data: agentsMock }, // Here was the problem.
        loading: true,
        error: 'Something went wrong D:'
    });

    render(<AgentsContainer />);

    const agentsCards = await screen.findAllByTestId('agent-card');

    expect(agentsCards).toHaveLength(3);
});

相关问题