jeudi 7 novembre 2019

Rendering a React component in a Jest test returns undefined

I have been trying to create a test with React, with the component TodoItems. It is just a regular Todolist with some basic features. When the test runs, it gives an error saying todos is undefined. The code in the test itself doesn't work as a result.

Test:

it("Tasks length increased by one when task is added.", () => {
  const { todos } = render(<TodoItems />);
  const todoLen = getByTestId(todos, "tasks");

  console.log(todos);
  expect(todoLen.toBe(1));
});

Component tested:

export default function Tasks() {
  let [tasks, setTasks] = useState([
    {
      content: "(Dette er en eksempelopppgave) "
    }
  ]);

  useEffect(() => {
    fetch("http://localhost:8080/all", {
      crossDomain: true,
      method: "GET",
      mode: "no-cors",
      credentials: "include"
    })
      .then(res => res.json())
      .then(function(response) {
        console.log("TodoItems is fetching.. ", response);
        if (response.status !== 200) {
          console.log("Fetching failed, response status: " + response.status);
          return;
        }
        response.json().then(function(data) {
          //was data instead of tasks, testing
          console.log(data, " is a response");
        });
      })
      .catch(function(err) {
        console.log("Fetch error: ", err);
      });
  }, []);

  // });

  let handleAddTask = task => {
    setTasks(tasks.concat(task));
    console.log("handleAddTask content: " + JSON.stringify(task));
  };

  let handleDeleteTask = id => {
    setTasks(tasks.filter(task => task.id !== id));
  };

  return (
    <div className="Tasks">
      <h2>Tasks</h2>
      <TaskList deleteTask={handleDeleteTask} tasks={tasks} />
      <TaskForm addTask={handleAddTask} />
      <Button onClick={reqListener}>Load</Button>
    </div>
  );
}

Aucun commentaire:

Enregistrer un commentaire