Skip to content

Instantly share code, notes, and snippets.

@nemrosim
Created March 27, 2022 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemrosim/90b8cc5a379ab28d5e3e702300ed01ba to your computer and use it in GitHub Desktop.
Save nemrosim/90b8cc5a379ab28d5e3e702300ed01ba to your computer and use it in GitHub Desktop.
import React from 'react';
import { render, screen } from '@testing-library/react';
import { App } from './App';
// ... other tests
describe('diff approaches', () => {
// helper
function textContentMatcher(text) {
return function (_content, node) {
const hasText = (node) => node.textContent === text;
const nodeHasText = hasText(node);
const childrenDontHaveText = Array.from(node?.children || []).every(
(child) => !hasText(child),
);
return nodeHasText && childrenDontHaveText;
};
}
const textContent = 'Edit src/App.tsx and save to reload.';
it('should render paragraph with text (1)', () => {
const { container } = render(<App />);
const p = container.getElementsByTagName(
'p',
)[0] as HTMLParagraphElement;
expect(p.textContent).toEqual(textContent);
expect(p).toHaveTextContent(textContent);
});
it('should render paragraph with text (2)', () => {
render(<App />);
expect(screen.getByRole('banner').children[1]).toHaveTextContent(
textContent,
);
});
it('should render paragraph with text (3)', () => {
render(<App />);
expect(screen.getByRole('img').nextElementSibling).toHaveTextContent(
textContent,
);
});
it('should render paragraph with text (4)', async () => {
render(<App />);
expect(
await screen.findByText(
textContentMatcher('Edit src/App.tsx and save to reload.'),
),
).toBeInTheDocument();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment