[英]TypeError: Cannot read property 'title' of undefined in ReactJS Jest Test
This is my code for Entry.js这是我的 Entry.js 代码
import React, { useState } from "react";
import EdiText from "react-editext";
export default function Entry({ entry, index, removeEntry }) {
//eslint-disable-next-line
const [value, setValue] = useState();
const handleSave = value => {
console.log(value);
setValue(value);
};
const data = entry.title;
return (
<div className="entry" style={{ width: "50%" }}>
<button
className="deleteBttn"
style={{ background: "red", float: "right" }}
onClick={() => removeEntry(index)}
>
x
</button>
<EdiText
className="editText"
value={data}
type="text"
onSave={handleSave}
buttonsAlign="before"
/>
</div>
);
}
This is the Entry.test.js.这是 Entry.test.js。 I want to check if the Entry component renders correctly.
我想检查 Entry 组件是否正确呈现。
import React from "react";
import Enzyme, { mount, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import ReactDOM from "react-dom";
import Entry from "../../components/Entry";
describe("Entry Component", () => {
beforeAll(() => {
Enzyme.configure({ adapter: new Adapter() });
});
it("renders correctly", () => {
shallow(<Entry data={"entry sample"} />);
const div = document.createElement("div");
ReactDOM.render(<Entry />, div);
});
});
When I run the test it returns an error of TypeError: Cannot read property 'title' of undefined当我运行测试时,它返回 TypeError 错误:无法读取未定义的属性“标题”
10 | setValue(value);
11 | };
> 12 | const data = entry.title;
What am I doing wrong?我究竟做错了什么?
You are not passing the entry
prop when mounting that component.安装该组件时,您没有传递
entry
道具。 Try logging out entry
first and see what it's value is.首先尝试注销
entry
,看看它的价值是什么。 If entry is undefined, you will get a runtime error trying to access a field of something that is undefined.如果条目未定义,您将在尝试访问未定义内容的字段时遇到运行时错误。
Change to改成
it("renders correctly", () => {
shallow(<Entry data={"entry sample"} entry={{title: "sometitle"}} />);
const div = document.createElement("div");
ReactDOM.render(<Entry entry={{title: "sometitle"}} />, div);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.