Today I was writing a unit test for a React component. The first test I begin with is the "match snapshot test".
Copied right away from the docs:
import renderer from 'react-test-renderer';
import { MyComponent } from './my-component';
test('render: match snapshot', () => {
const render = renderer.create(<MyComponent />).toJSON();
expect(render).toMatchSnapshot();
})
This will create a .snap
(text) file:
src
βββ components
βΒ Β βββ __snapshots__ # <== creates this directory
βΒ Β βΒ Β βββ my-component.test.tsx.snap # <== snapshot
βΒ Β βββ my-component
βΒ Β βΒ Β βββ my-component.scss
βΒ Β βΒ Β βββ my-component.tsx
βΒ Β βΒ Β βββ my-component.test.tsx
βΒ Β ...
Using react-test-renderer
library:
So far so good. This is what it's documented.
Today I asked GitHub Copilot π€ to fill my test file. It suggested me something different instead:
-import renderer from 'react-test-renderer';
+import { render } from '@testing-library/react';
import { MyComponent } from './my-component';
test('render: match snapshot', () => {
- const render = renderer.create(<MyComponent />).toJSON();
- expect(render).toMatchSnapshot();
+ Β const { asFragment } = render(<MyComponent />);
+ expect(asFragment()).toMatchSnapshot();
})
Which doesn't need the extra dependency react-test-renderer
.
I was like "wait, does this work?"
It does.
It creates the exact file structure. So I came to the docs checking for the differences between asFragment()
and renderer.create().toJSON()
. But I haven't found good documentation on this regard.
Copilot's code works. Saves me one dependency. Proposed me a solution that isn't - well - documented and, in the end, has surpassed me.
This is interesting at the very least.
--
Thanks for reading π.
Top comments (0)