"Unable to find an element with the text.." 在反应测试期间

"Unable to find an element with the text.." during react testing

我有一个小型 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>
    </>
  );
}

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