Testing Tips & Tricks
Here are some tips and tricks for testing with Jest and React Testing Library.
Output Rendered DOM to File
Sometimes you just can't seem to get a test to work correctly and you really wish you could see if the page rendered correctly.
import fs from 'fs';
import { render } from '@testing-library/react';
test('write rendered HTML to file', () => {
const { container } = render(
<main className="dc-main-content">
<h1>Welcome to My Page</h1>
<p>This is the main content.</p>
</main>
);
// Write the rendered HTML to a file
fs.writeFileSync('rendered.html', container.innerHTML);
});
or you can do soemthing like this
const someElement = document.querySelector('.some-class');
fs.writeFileSync('some-class.html', someElement.outerHTML);
In either case, the file will write to the root of your project.
You can manually choose the file path to write the file to by passing the path to fs.writeFileSync()
.
fs.writeFileSync('./nick_test_files/mainElement.html', mainElement.outerHTML);
If you place the file in a directory, make sure the directory exists or you will get an error.
Possible Multiple Instances of Text
It's common to check if there is an instance of a string on the page. But what if there are multiple instances of the string?
await waitFor(() => {
// expected texts
const expectedTexts = [
'Keyword',
'Another String',
'This string could show up multiple times',
]
// do this loop to account for multiple instances of a text
expectedTexts.forEach(text => {
const instancesOfEachText = screen.getAllByText(text)
instancesOfEachText.forEach(instance => {
expect(instance).toBeInTheDocument()
})
})
})
Debug Text Matching
If you're having trouble matching text, you can debug the texts being rendered with a partial match.
// Debug the texts being rendered
const allTexts = screen
.getAllByText(/Some partial match text/i)
.map(node => node.textContent)
console.log('Texts found:', allTexts)
And it will log all the matching texts to the console. This is particularly useful if you've verified the text is rendering to the DOM with the DOM trick above and it's still not matching.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.