无法找到带有文本的元素:“myText"使用 react-testing-library 时出错 [英] Unable to find an element with the text: "myText" error when using react-testing-library

查看:21
本文介绍了无法找到带有文本的元素:“myText"使用 react-testing-library 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 react-testing-library 与 React 和 Jest 一起使用,但我的一个测试失败了,我认为它与 className 道具上的正则表达式有关 在测试文件上.

下面我附上了各自的测试 &组件文件.

另外,有没有办法用这个库进行snapshot 测试?我觉得我的测试由于某种原因没有完成.

//Image.js 组件//@流动import * as React from "react";从样式组件"导入样式;const StyledImage = styled.img`最大宽度:${props =>props.imageWidth ||100}%;`;类型道具 = {imageAlt:字符串,imageSrc: 字符串 |布尔值 |功能,类名?:字符串,StyledImage:React.Element};const Image = (props: 道具) =>{const { imageAlt, imageSrc, className } = props;返回 (<风格化图片{...道具}类名={类名}src={imageSrc}alt={imageAlt}/>);};导出默认图像;//Image.test.js从反应"导入反应;从react-testing-library"导入{渲染,清理};从../Image"导入图像;描述(<图像/>组件",()=> {afterEach(清理);describe("组件作为一个整体", () => {it("使用 src、alt 和 className 渲染图像", () => {const testProps = {imageAlt:一些随机字符串",imageSrc: ""/* [ASK]: 如何测试这个 */,className: "imageDescripton"/* [ASK]: 如何测试这个 */};const { getByAltText } = render(<Image {...testProps}/>);const { getByText } = render(<Image {...testProps}/>);const imageAltNode = getByAltText(testProps.imageAlt);const imageClassNameNode = getByText(`${testProps.className}`);//[FAIL]: 因错误而失败.无法找到带有文本的元素:imageDescripton.正则问题?期望(imageAltNode).toBeDefined();期望(图像类名称节点).toBeDefined();});});});

完整的错误日志:

无法找到带有文本的元素:imageDescripton.这可能是因为文本被多个元素分解了.在这种情况下,您可以为您的文本匹配器提供一个功能,使您的匹配器更加灵活.<身体><div><imgalt="一些随机字符串"class="imageDescripton Image__StyledImage-sc-1icad3x-0 judnkv"源代码=""/>

<div><imgalt="一些随机字符串"class="imageDescripton Image__StyledImage-sc-1icad3x-0 judnkv"源代码=""/>

18 |19 |const imageAltNode = getByAltText(testProps.imageAlt);>20 |const imageClassNameNode = getByText(`${testProps.className}`);//[FAIL]: 因错误而失败.无法找到带有文本的元素:imageDescripton.正则问题?|^21 |22 |期望(imageAltNode).toBeDefined();23 |期望(图像类名称节点).toBeDefined();

解决方案

getByText 查找节点内的文本.所以在这个例子中:

bar

文字是bar.

getByAltText 是查找图像的最佳方式.另一种方法是使用 getByTestId.

如果必须按类查找元素怎么办?在这些情况下,您可以使用 render 返回的 container.container 只是一个 DOM 节点,所以你可以做

const { container } = render()container.querySelector('.my-class')

请注意,您不必使用 toBeDefined(),您可以使用更惯用的 toBeInTheDocument().确保您先安装 jest-dom.

<小时>

如何制作快照?同样,您可以使用 container.在这种情况下,您想要第一个孩子.

expect(container.firstChild).toMatchSnapshot()

I'm trying to use react-testing-library with React and Jest but one of my tests are failing and I think it has something to do with the regex on the className prop on the test file.

Below I have attached the respectives test & component files.

Also, is there a way to snapshot testing with this library? I feel that my test is not complete for some reason.

// Image.js Component


// @flow
import * as React from "react";
import styled from "styled-components";

const StyledImage = styled.img`
  max-width: ${props => props.imageWidth || 100}%;
`;

type Props = {
  imageAlt: string,
  imageSrc: string | boolean | Function,
  className?: string,
  StyledImage: React.Element<typeof StyledImage>
};

const Image = (props: Props) => {
  const { imageAlt, imageSrc, className } = props;
  return (
    <StyledImage
      {...props}
      className={className}
      src={imageSrc}
      alt={imageAlt}
    />
  );
};

export default Image;



// Image.test.js 


import React from "react";
import { render, cleanup } from "react-testing-library";
import Image from "../Image";

describe("<Image /> component", () => {
  afterEach(cleanup);

  describe("Component as a whole", () => {
    it("renders the image with a src, alt and a className ", () => {
      const testProps = {
        imageAlt: "some random string",
        imageSrc: "" /* [ASK]: How to test this */,
        className: "imageDescripton" /* [ASK]: How to test this */
      };

      const { getByAltText } = render(<Image {...testProps} />);
      const { getByText } = render(<Image {...testProps} />);

      const imageAltNode = getByAltText(testProps.imageAlt);
      const imageClassNameNode = getByText(`${testProps.className}`); // [FAIL]: Fails with error.  Unable to find an element with the text: imageDescripton. Regex problem?

      expect(imageAltNode).toBeDefined();
      expect(imageClassNameNode).toBeDefined();
    });
  });
});

Complete error log:

Unable to find an element with the text: imageDescripton. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

<body>
  <div>
    <img
      alt="some random string"
      class="imageDescripton Image__StyledImage-sc-1icad3x-0 judnkv"
      src=""
    />
  </div>
  <div>
    <img
      alt="some random string"
      class="imageDescripton Image__StyledImage-sc-1icad3x-0 judnkv"
      src=""
    />
  </div>
</body>

  18 |
  19 |       const imageAltNode = getByAltText(testProps.imageAlt);
> 20 |       const imageClassNameNode = getByText(`${testProps.className}`); // [FAIL]: Fails with error.  Unable to find an element with the text: imageDescripton. Regex problem?
     |                                  ^
  21 |
  22 |       expect(imageAltNode).toBeDefined();
  23 |       expect(imageClassNameNode).toBeDefined();

解决方案

getByText looks for the text inside a node. So in this example:

<div class="foo">bar</div>

the text is bar.

getByAltText is the best way to find an image. Another way is to use getByTestId.

What if you must find an element by class? In these cases, you can use container which is returned by render. container is just a DOM node so you can do

const { container } = render(<MyComponent />)
container.querySelector('.my-class')

Note that you don't have to use toBeDefined(), you can use toBeInTheDocument() which is more idiomatic. Make sure you install jest-dom first.


How to make a snapshot? Again, you can use container. In this case you want the first child.

expect(container.firstChild).toMatchSnapshot()

这篇关于无法找到带有文本的元素:“myText"使用 react-testing-library 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆