这是我的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>
);
}
这是Entry.test.js。我想检查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);
});
});
当我运行测试时,它返回错误 TypeError:无法读取未定义的属性“ title”
10 | setValue(value);
11 | };
> 12 | const data = entry.title;
我在做什么错了?
答案 0 :(得分:0)
安装该组件时,您没有通过entry
道具。尝试先注销entry
,看看它的价值是什么。如果条目未定义,则在尝试访问未定义内容的字段时会遇到运行时错误。
更改为
it("renders correctly", () => {
shallow(<Entry data={"entry sample"} entry={{title: "sometitle"}} />);
const div = document.createElement("div");
ReactDOM.render(<Entry entry={{title: "sometitle"}} />, div);
});