简体   繁体   中英

TypeError: Cannot read property 'title' of undefined in ReactJS Jest Test

This is my code for 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. I want to check if the Entry component renders correctly.

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

  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. Try logging out entry first and see what it's value is. 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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM