Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[new rule] Require that TypeScript tests use a typed jest.mock factory #1313

Closed
NotWoods opened this issue Dec 24, 2022 · 2 comments · Fixed by #1314
Closed

[new rule] Require that TypeScript tests use a typed jest.mock factory #1313

NotWoods opened this issue Dec 24, 2022 · 2 comments · Fixed by #1314

Comments

@NotWoods
Copy link
Contributor

A new rule that requires type-checking.

jest.mock and jest.doMock take an optional generic, representing the return type of the factory. For example,

// The optional type argument provides typings for the module factory
jest.mock<typeof import('../moduleName')>('../moduleName', () => {
  return jest.fn(() => 42);
});

Without specifying typeof import('../moduleName'), Jest's types doesn't know what the module looks like and will allow anything to be returned in the factory.

I'd like to have an ESLint rule to enforce that the generic parameter is used whenever a factory function is used. Jest auto-mocks (no factory) and virtual mocks (no corresponding actual module) don't need to have the generic parameter.

Examples of incorrect code for this rule:

jest.mock('../moduleName', () => {
  return jest.fn(() => 42);
});
jest.mock('./module', () => ({
  ...jest.requireActual('./module'),
  foo: jest.fn()
}));
jest.mock('random-num', () => {
  return jest.fn(() => 42);
});

Examples of correct code for this rule:

// Uses typeof import()
jest.mock<typeof import('../moduleName')>('../moduleName', () => {
  return jest.fn(() => 42);
});
jest.mock<typeof import('./module')>('./module', () => ({
  ...jest.requireActual('./module'),
  foo: jest.fn()
}));

// Uses custom type
jest.mock<() => number>('random-num', () => {
  return jest.fn(() => 42);
});
// No factory
jest.mock('random-num');
// Virtual mock
jest.mock(
  '../moduleName',
  () => {
    return jest.fn(() => 42)
  },
  {virtual: true},
);

Auto-fixable: Yes

@G-Rath
Copy link
Collaborator

G-Rath commented Dec 24, 2022

This sounds ok, and won't require type-checking, just @typescript-eslint/parser as generics are syntax so they're represented as AST nodes.

@github-actions
Copy link

🎉 This issue has been resolved in version 27.2.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants