debugging react任务管理应用程序错误:TestingLibraryElementError:无法通过以下方式找到元素:[data-testid=“add-task-form”]

mm5n2pyu  于 2023-10-24  发布在  React
关注(0)|答案(1)|浏览(147)

我试图测试我的基本任务管理器应用程序与React:这里是组件和测试文件分别:

组件(AddTask.js)

import React, { useState } from 'react';

function AddTask({ addTask }) {
  const [task, setTask] = useState({ title: '', description: '' });
  const [successMessage, setSuccessMessage] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setTask({ ...task, [name]: value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (task.title.trim() === '') {
      setErrorMessage('Task title is required');
      return;
    }

    try {
      await addTask(task);
      setSuccessMessage('Task added successfully');
      setTask({ title: '', description: '' });
      setErrorMessage(''); // Clear any previous error messages
    } catch (error) {
      setErrorMessage('Failed to add the task');
    }
  }

  return (
    <div className="add-task">
      <h2 data-testid="add-task-heading">Add Task</h2>
      {successMessage && <div className="success-message">{successMessage}</div>}
      {errorMessage && <div className="error-message">{errorMessage}</div>}
      <form data-testid="add-task-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="title">Title:</label>
          <input
            type="text"
            id="title"
            name="title"
            value={task.title}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-group">
          <label htmlFor="description">Description:</label>
          <textarea
            id="description"
            name="description"
            value={task.description}
            onChange={handleInputChange}
          />
        </div>
        <button type="submit">Add Task</button>
      </form>
    </div>
  );
}

export default AddTask;

Test(AddTask.test.js)

import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import AddTask from '../components/AddTask'; // Import your AddTask component

// ...

test('displays an error message when submitting an empty form', async () => {
  const form = screen.getByTestId('add-task-form');
  const titleInput = screen.getByLabelText('Title:');
  const addButton = screen.getByText('Add Task');

  // Use waitFor to wait for the addButton to become available
  await waitFor(() => {
    expect(form).toBeInTheDocument();
    expect(titleInput).toBeInTheDocument();
    expect(addButton).toBeInTheDocument();
  });

  // Click the Add Task button to submit the empty form
  fireEvent.click(addButton);

  // Check if the error message is displayed
  const errorMessage = screen.getByText('Task title is required');
  expect(errorMessage).toBeInTheDocument();
});


test('displays an error message when submitting an empty form', () => {
  // Select the form element by using its unique data-testid attribute
  const form = screen.queryByTestId('add-task-form');

  // Inside the form, select the input fields and the Add Task button
  const titleInput = screen.queryByLabelText('Title:');
  const addButton = screen.queryByText('Add Task');

  // Click the Add Task button to submit the empty form
  fireEvent.click(addButton);

  // Check if the error message is displayed
  const errorMessage = screen.queryByText('Task title is required'); // Adjust the error message text as needed
  expect(errorMessage).toBeInTheDocument();
});

当我运行npm test时,我得到以下错误:
FAILsrc/tests/AddTask.test.js(5.768s)●提交空表单时显示错误消息

TestingLibraryElementError: Unable to find an element by: [data-testid="add-task-form"]

Ignored nodes: comments, script, style
<body />

   6 |
   7 | test('displays an error message when submitting an empty form', async () => {
>  8 |   const form = screen.getByTestId('add-task-form');
     |                       ^
   9 |   const titleInput = screen.getByLabelText('Title:');
  10 |   const addButton = screen.getByText('Add Task');
  11 |

  at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
  at node_modules/@testing-library/dom/dist/query-helpers.js:76:38
  at node_modules/@testing-library/dom/dist/query-helpers.js:52:17
  at getByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:95:19)
  at Object.<anonymous> (src/__tests__/AddTask.test.js:8:23)

我已经尝试了一切通过测试,我已经检查了一切是否正确导入导出。如果package.json文件是好的,重新安装更新库等。请帮助!

dxpyg8gm

dxpyg8gm1#

好吧,你正在尝试访问你的表单而不呈现任何东西,请添加render调用,如下面的例子:

import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import AddTask from '../components/AddTask'; 

test('displays an error message when submitting an empty form', async () => {
  render(<AddTask />); // This needs to be added
  const form = screen.getByTestId('add-task-form');
  // ...
});

查看文档以查看示例:https://testing-library.com/docs/queries/bytestid/

相关问题