javascript - 在 Jest 测试中渲染 React 组件返回 undefined

标签 javascript reactjs testing jestjs undefined

我一直在尝试使用 React 组件 TodoItems 创建一个测试。它只是具有一些基本功能的常规 Todolist。当测试运行时,它给出了一个错误,说 todos 是未定义的。结果,测试中的代码本身不起作用。

测试:

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));
});

测试的组件:

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>
  );
}

编辑(完整的测试代码):

import React from "react";
import renderer from "react-test-renderer";
import TodoItems from "../components/TodoItems.js";
import { render, fireEvent, getByTestId } from "@testing-library/react";
import App from "../App.js";

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

  expect(container).toBeDefined();
  expect(todos).toHaveLength(1);
});

最佳答案

当您使用 @testing-library/react 进行测试时,render 方法会返回带有一堆有用的 getter 的 container,所以你可以这样做:

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

  expect(container).toBeDefined();
  expect(todos).toHaveLength(1);
});

要使 const todos = getByTestId("tasks"); 行正常工作,您需要向组件添加 data-testid 属性:

 <TaskList deleteTask={handleDeleteTask} tasks={tasks} data-testid="tasks"/>

关于javascript - 在 Jest 测试中渲染 React 组件返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58752198/

相关文章:

javascript - 如何将 document.cookie 替换为 Cookies.set (使用最新的 jquery cookie 插件)

javascript - 如何在 jQuery 中绕 z 轴旋转图像?

javascript - 仅根据类别切换某些元素

javascript - 如何在 NodeJs 中更改 package.json 中的主文件

spring - 使用 junit 测试端点(POST 方法)

javascript - `alert($(' table tr ').html());` 只显示一行表

html - 模式背景元素的正确 HTML 角色和其他相关属性 (TypeScript React)

javascript - ReactJS 教程 - 评论表单未发布到本地服务器

angularjs - Protractor :异步超时,我认为是因为它找不到元素

testing - 与自动化测试用例相比,使用 CodedUI 测试的好处(通过 Action 记录)