我有一個小型 React/TypeScript/GraphQL 應用程式,它連接到 API、獲取產品并將它們顯示在頁面上。
我正在嘗試創建一個測驗,通過使用 來檢查產品名稱是否在 GraphQL 模擬之后的檔案中getByText,但我不斷收到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();
});
產品卡.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>
</>
);
}
uj5u.com熱心網友回復:
MockedProvider如果您只是在測驗一個“啞”組件(也就是只呈現一些 HTML 并且沒有其他邏輯的組件),那么您似乎不需要。只有MockedProvider在測驗使用useQueryor的組件時才需要useMutation,在這種情況下,這些鉤子將回傳您提供的 mock.result 值。嘗試完全洗掉 MockedProvider 并僅使用一些道具渲染組件,看看是否有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368197.html
標籤:javascript 反应 玩笑 图形 阿波罗
上一篇:呈現特定JSON屬性的問題
