Jest.js TypeError:Cannot destruct property 'data' of '(intermediate value)',因为它是未定义的- React测试库

hvvq6cgz  于 11个月前  发布在  Jest
关注(0)|答案(2)|浏览(621)

我在使用React测试库测试React组件时遇到问题。该组件涉及使用Axios获取数据。测试失败,并出现以下错误:

TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined.

      11 |
      12 |         const fetchFollowers = async () => {
    > 13 |             const { data } = await axios.get("https://randomuser.me/api/?results=5")
         |                     ^
      14 |             setFollowers(data.results)
      15 |         }
      16 |

      at fetchFollowers (src/components/FollowersList/FollowersList.js:13:21)

字符串
在我展示测试套件之前,我只是遵循了这个你可以轻松克隆的git存储库的教程。
https://github.com/harblaith7/React-Testing-Library-Net-Ninja
所以我的测试套件看起来像这样:
FollowerList.test.js:

import { render, screen, fireEvent } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import FollowersList from "../FollowersList";

const MockFollowersList = () => {
    return (
        <BrowserRouter>
            <FollowersList />
        </BrowserRouter>
    )
}

describe("FollowersList", () => {

    beforeEach(() => {
        // console.log("RUNS BEFORE EACH TEST")
        jest.mock("../../../__mocks__/axios")
    })

    // beforeAll(() => {
    //     console.log("RUNS ONCE BEFORE ALL TESTS")
    // })

    // afterEach(() => {
    //     console.log("RUNS AFTER EACH TEST")
    // })

    // afterAll(() => {
    //     console.log("RUNS ONCE AFTER ALL TESTS")
    // })

    it('should fetch and render input element', async () => {
        render(
            <MockFollowersList />
        );
        const followerDivElement = await screen.findByTestId(`follower-item-0`)
        expect(followerDivElement).toBeInTheDocument();
    });
    
    it('should fetch and render input element2', async () => {
        render(
            <MockFollowersList />
        );
    
        const followerDivElement = await screen.findByTestId(`follower-item-0`)
        expect(followerDivElement).toBeInTheDocument();
    });
})


axios.js inmocks

const mockResponse = {
    data: {
        results: [
            {
                name: {
                    first: "Laith",
                    last: "Harb"
                },
                picture: {
                    large: "https://randomuser.me/api/portraits/men/59.jpg"
                },
                login: {
                    username: "ThePhonyGOAT"
                }
            }
        ]
    }
}

export default {
    get: jest.fn().mockResolvedValue(mockResponse)
}


我在代理人后面工作,但我不认为这是问题所在。如果你能给我建议,我会很感激的!
问候

scyqe7ek

scyqe7ek1#

正在读取__mocks__/axios.js中的模拟版本的axios,但问题是react-scripts在运行测试时添加了jest配置resetMocks: true
这有效地重置了所有的模拟实现,在执行测试之前删除了所有的假实现。
您可以在package.json中覆盖此配置:

"jest": {
    "resetMocks": false
}

字符串

另一种解决方案,如果您不想更改此配置,可以在测试中模拟实现:

import axios from 'axios';
[...]

it('should fetch and render input element', async () => {
    axios.get = jest.fn().mockResolvedValue(<your_mock_response>);

    render(
        <MockFollowersList />
    );
    const followerDivElement = await screen.findByTestId(`follower-item-0`)
    expect(followerDivElement).toBeInTheDocument();
});


由于这个mock是在jest配置执行重置之后执行的,因此它允许您添加伪实现。

up9lanfz

up9lanfz2#

const fetchFollowers = async () => {

    const response= await (await axios.get("https://randomuser.me/api/? 
    results=5")).data;

    setFollowers(response.results);
}

字符串

相关问题