TypeError:预期容器是一个Element,一个Document或一个DocumentFragment但得到了字符串

问题描述

我正在尝试使用RTL运行以下测试用例,并且测试失败,并显示错误“ TypeError:期望容器是Element,Document或DocumentFragment但得到了字符串”。我尝试搜索解决方案,但找不到解决方案。

describe("Feedback Commponent",()=>{
  it('should throw error when feedback textbox is empty',() => {
    const { getByLabelText} = render(<Contact />);

    fireEvent.change(getByLabelText('Feedback'),{
      target: { value: '' },});

    fireEvent.blur(getByLabelText('Feedback'));
    debug();

    expect(getByTestId('feedback-error')).toBe(
      'Please Enter Your Feedback'
    );
  });
});

上面的代码段假设要测试反馈表单,仅针对反馈文本框,如果为空并且当用户从文本框中移出焦点时,应该出现错误,指出“请输入您的反馈”

解决方法

您似乎直接从测试库中导入了 getByTestId 方法,而不是像使用 getByLabelText 那样从渲染中解构它。 getByTestId,根据文档是:

getByTestId(
  // If you're using `screen`,then skip the container argument:
  container: HTMLElement,text: TextMatch,options?: {
    exact?: boolean = true,normalizer?: NormalizerFn,}): HTMLElement

所以它期望第一个参数是 HTML 容器,因此错误。 一种解决方案是也解构 getByTestId:

const { getByLabelText,getByTestId } = render(<Contact />);

另一种是使用屏幕,如文档所建议的:

import { screen } from '@testing-library/react';
...

expect(screen.getByTestId('feedback-error')).toBe(
  'Please Enter Your Feedback'
);

在这种情况下,第一个 'container' 参数被跳过,字符串 'feedback-error' 被视为测试 id 'text' 参数。文档: https://testing-library.com/docs/queries/bytestid

,

我通过将断言更改为

解决了该问题
expect(getByText('Please Enter Your Feedback')).toBeInTheDocument();

来自

 expect(getByTestId('feedback-error')).toBe('Please Enter Your Feedback');

我还注意到我有setupTest.js文件

import '@testing-library/jest-dom/extend-expect';

missing,它添加了用于在DOM节点上声明的自定义笑话匹配器,因此在添加了上述更改之后,我的测试用例通过了

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...