I have been getting better at unit testing nodejs code with jest but now i'm moving into RTL for UI testing and i had something i'm not sure about.
Is there some standard or way you guys assert the structure of you components? for example, the lets assume this component that has multiple nested ordered and unordered list, i was looking into that and although i can simply do assert on a screen.findByText on some text in that component of nested list, it doesnt help with the structure of it, like if its nested list or nested divs or anything, it doesnt tell me where that text is in relation to what i would expect to see only that it exist, (maybe the text is in the second nested list and not the root list or some other nested list, so how would u handle that?
this is one example but i even have data tables with tables within it and idk how to make sure the structure is correct.
Thank you.
CodePudding user response:
You are looking for Snapshot Testing:
Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.
snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct.
E.g.
index.test.tsx
:
import { render } from '@testing-library/react';
import React from 'react';
const TestComp = () => {
return (
<>
<ul>
{[
{ name: 'apple', products: ['a', 'b', 'c'] },
{ name: 'sony', products: ['x', 'y', 'z'] },
].map((brand) => (
<li key={brand.name}>
{brand.name}
<ul>
{brand.products.map((p) => (
<li key={p}>{p}</li>
))}
</ul>
</li>
))}
</ul>
</>
);
};
describe('75194829', () => {
test('should pass', () => {
const { container } = render(<TestComp />);
expect(container).toMatchSnapshot();
});
});
__snapshots__/index.test.tsx.snap
:
// Jest Snapshot v1, xxxxx
exports[`75194829 should pass 1`] = `
<ul>
<li>
apple
<ul>
<li>
a
</li>
<li>
b
</li>
<li>
c
</li>
</ul>
</li>
<li>
sony
<ul>
<li>
x
</li>
<li>
y
</li>
<li>
z
</li>
</ul>
</li>
</ul>
`;
Tip: To get the root element of your rendered element, use
container.firstChild
.