【问题标题】:"Unable to find an element with the text.." during react testing“无法找到带有文本的元素..”在反应测试期间
【发布时间】:2022-01-05 08:46:30
【问题描述】:

我有一个小型 React/TypeScript/GraphQL 应用程序,它连接到 API、获取产品并将它们显示在页面上。

我正在尝试使用getByText 创建一个测试,检查产品名称是否在 GraphQL 模拟之后的文档中,但我不断收到TestingLibraryElementError: Unable to find an element with the text: iPad 5g. 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.

我也尝试使用getByRole(见下文),但这给了我错误TestingLibraryElementError: Unable to find an accessible element with the role "paragraph" and name '/month to month/i'

有没有更好的方法来做到这一点?如何检查产品名称是否正确呈现?感谢您的帮助。

ProductCard.test.js

import React from "react";
import { render, screen } from "@testing-library/react";
import TestRenderer from 'react-test-renderer';
import { MockedProvider } from '@apollo/client/testing';
import ProductCard from "../ProductCard";
import { LOAD_PRODUCTS } from "../GraphQL/Queries";
import '@testing-library/jest-dom';

it('renders ProductCard successfully', async () => {
  const productMock = {
    request: {
      query: LOAD_PRODUCTS,
    },
    result: {
      data: { products: { productName: 'iPad 5g', code: 'i5g', price: 599.99 } },
    },
  };

  const component = TestRenderer.create(
    <MockedProvider mocks={[productMock]} addTypename={false}>
      <ProductCard displayName={productMock.result.data.products.productName} price={productMock.result.data.products.price} />
    </MockedProvider>,
  );
  await new Promise(resolve => setTimeout(resolve, 0));  
  expect(screen.getByText(`iPad 5g`)).toBeInTheDocument();
  // expect(screen.getByRole('paragraph', { name: /iPad 5g/i })).toBeInTheDocument();
});

ProductCard.tsx

// imports 
// ... 
// ...

// TypeScript types 
// ... 
// ... 

const ProductCard: React.FC<Props> = ({ productName, price }) => {

  return (
    <>
      <Typography>{productName}</Typography>
      <Typography>{price}</Typography>
      <Typography><p>Great new features</p></Typography>
      <Button>Buy Now</Button>
    </>
  );
}

【问题讨论】:

    标签: javascript reactjs jestjs graphql apollo


    【解决方案1】:

    如果您只是在测试一个“哑”组件(也就是只呈现一些 HTML 并且没有其他逻辑的组件),那么看起来您不需要 MockedProvider。如果您正在测试使用useQueryuseMutation 的组件,则只需要MockedProvider,在这种情况下,这些挂钩将返回您提供的mock.result 值。尝试完全删除 MockedProvider 并使用一些道具渲染组件,看看是否有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2020-04-10
      • 2020-03-01
      相关资源
      最近更新 更多