我一直在尝试使用组件TodoItems用React创建一个测试。它只是具有一些基本功能的常规Todolist。测试运行时,会显示一条错误消息,说明待办事项尚未定义。结果,测试中的代码本身不起作用。
测试:
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);
});
答案 0 :(得分:0)
当您使用|-Folder
|--Partition Keys
|---Columns
|----Rows_1-100.snappy.parquet
|----Rows_101-200.snappy.parquet
进行测试时,@testing-library/react
方法会返回render
以及许多有用的吸气剂,因此您可以执行以下操作:
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