DEV Community

Cover image for GitHub Copilot discovered me something isn't documented
Manuel Artero Anguita 🟨
Manuel Artero Anguita 🟨

Posted on

2

GitHub Copilot discovered me something isn't documented

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();
})
Enter fullscreen mode Exit fullscreen mode

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
│   ...
Enter fullscreen mode Exit fullscreen mode

Using react-test-renderer library:

Image description

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();
})
Enter fullscreen mode Exit fullscreen mode

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 💚.

Retry later

Top comments (0)

Retry later
Retry later