开玩笑 - 无法读取未定义的属性(阅读' map')使用I18Next时
我对测试还很陌生,我在我的应用程序中使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论