例如
// MyComponent.jsx
import React from 'react';
const MyComponent = () => (
<div>
<h1 data-testid="header">Hello, World!</h1>
<div data-testid="container">
<p data-testid="paragraph">This is a paragraph within the container.</p>
</div>
</div>
);
export default MyComponent;
within的用法
const { getByRole,getByTestId } = within(Element)
// MyComponent.test.jsx
import React from 'react';
import { render,within } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'; // 用于jest-dom的匹配器
import MyComponent from './MyComponent';
test('renders paragraph within container', () => {
const { getByTestId } = render(<MyComponent />);
const container = getByTestId('container');
const { getByTestId: getByTestIdWithin, getByRole } = within(container);
const paragraph = getByTestIdWithin('paragraph');
expect(paragraph).toHaveTextContent('This is a paragraph within the container.');
});
Top comments (0)