开玩笑 - 无法读取未定义的属性(阅读' map')使用I18Next时

发布于 2025-01-17 20:48:31 字数 1343 浏览 3 评论 0原文

我对测试还很陌生,我在我的应用程序中使用 i18next,但是当我尝试测试使用 .map() 的组件时,我收到错误:无法读取未定义的属性。我应该如何编写测试以避免出现此错误?

Component.js - myArr 来自 json 文件。

MyComponent = () => {
return(
  <div data-testid="comp">
    {t("myArr", { returnObjects: true}).map(({ name, href, target }) => (
                <div key={name} >
                    <Link href={href}>
                        <a 
                            target={target}
                            onClick={() => handleClick()}>
                            {name}
                        </a>
                    </Link>
                </div>
            ))}
 )
}

组件.test.js

import React from "react";
import {render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

import MyComp from ".";

jest.mock("next/router", () => ({
    useRouter() {
        return {
            local: "",
            asPath: "",
        };
    },
}));


describe("MyComp", () => {
    it("should render myComponent", () => {
        const { getByTestId } = render(
            <myComponent menuOpen={false} setBurgerOpen={jest.fn()} t={jest.fn()}/>
        );

        const myComp = getByTestId("comp");

        expect(myComp).toBeVisible();
        
    });
});

I'm quite new to testing and I'm using i18next in my app but when I try to test components where I use .map() I receive an error of cannot read properties of undefined. How should I write the test so I don't get this error?

Component.js - the myArr is from a json file.

MyComponent = () => {
return(
  <div data-testid="comp">
    {t("myArr", { returnObjects: true}).map(({ name, href, target }) => (
                <div key={name} >
                    <Link href={href}>
                        <a 
                            target={target}
                            onClick={() => handleClick()}>
                            {name}
                        </a>
                    </Link>
                </div>
            ))}
 )
}

Component.test.js

import React from "react";
import {render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

import MyComp from ".";

jest.mock("next/router", () => ({
    useRouter() {
        return {
            local: "",
            asPath: "",
        };
    },
}));


describe("MyComp", () => {
    it("should render myComponent", () => {
        const { getByTestId } = render(
            <myComponent menuOpen={false} setBurgerOpen={jest.fn()} t={jest.fn()}/>
        );

        const myComp = getByTestId("comp");

        expect(myComp).toBeVisible();
        
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文