如何将数据传递到在Jest中具有嵌套组件的函数中?

问题描述 投票:0回答:1

这是我的CustomEntry组件,我要在其中测试addEntry函数。

import Entry from "./Entry";
import CreateEntry from "./CreateEntry";

function CustomEntry() {
  const [entries, setEntries] = useState([]);

  const addEntry = title => {
    const newEntries = [...entries, { title, completed: false }];
    setEntries(newEntries);
  };

  return (
    <div className="entry-container">
      <div className="create-entry">
        <CreateEntry addEntry={addEntry} />
      </div>
      <div className="entry">
        {entries.map((entry, index) => (
          <Entry
            entry={entry}
            index={index}
            key={index}
          />
        ))}
      </div>
    </div>
  );
}

export default CustomEntry;

这是CreateEntry组件

const handleSubmit = e => {
    if (!value) return;
    addEntry(value);
    setValue("");
  };
      <form onSubmit={handleSubmit}>
        <input
          name="customEntryInput"
          type="text"
          className="input"
          value={value}
          onChange={e => setValue(e.target.value)}
        />
       </form>

如何测试调用单独组件的addEntry函数?

javascript reactjs jestjs enzyme
1个回答
0
投票

您可以尝试这个吗?我认为您还正确设置了所有其他内容。

我不确定我们是否会在范围内使用正确的“ this”,但尝试这样做,如果仍然无法正常工作,我们将尝试在范围内获得正确的“ this”。

const handleSubmit = e => {
    if (!value) return;
    this.props.addEntry(value);
    setValue("");
  };
© www.soinside.com 2019 - 2024. All rights reserved.