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

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay