vercel / style-guide

Vercel's engineering style guide
Mozilla Public License 2.0
1.18k stars 29 forks source link

feat(eslint): sort testing mocks to top of file #62

Closed adrianbw closed 10 months ago

adrianbw commented 1 year ago

In our unit tests, we often have a *.test.mocks file containing the mocking that we're doing for a test. For example, we might do this:

export const query: Record<string, string | boolean> = {
  next: '/home',
};

export const router = {
  isReady: false,
  pathname: '/login',
  query,
  replace: jest.fn(),
  push: jest.fn(),
};
export const useRouter = jest.fn(() => router);

jest.doMock('next/router', () => ({
  useRouter,
  __esModule: true,
  default: router,
}));

These mocks must be the first thing imported in the test file or else they won't be in place when the test imports the actual component.

If we don't import anything from the mocks file, then eslint is perfectly happy with the mock import being first. However, as in the example above, we might want to import useRouter so that we can change its return value in different tests. If we do, then eslint will warn that the import order is incorrect.

This PR fixes that issue by adding a pathGroups entry that captures ./*.test.mocks imports and requires them to be before builtin, which is the first item in our groups property.

mrmckeb commented 10 months ago

At this is a fairly bespoke naming system (.mocks), we think this should instead be an override (or config) in any repos that use a system like this.