DEV Community

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

Posted on

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 πŸ’š.

Top comments (0)