jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.12k stars 6.44k forks source link

[Feature]: warning for duplicated `jest.mock` #15267

Open canalun opened 1 month ago

canalun commented 1 month ago

πŸš€ Feature Proposal

Display a warning in CLI when detecting jest.mock is used more than once for the same module in one test.

Motivation

When using jest.mock more than once for the same module in one test, which result of these jest.mocks will be used depends on internal implementations of the modules used in the test.

Especially, it can occur when the team separate functions and classes only for tests as helper files.

This feature request seeks to address this by promoting clear guidelines on CLI when detecting this situation.

Example

test.js

import { a } from 'a.js'
import { helper } from 'helper.js'

jest.mock('mockedModule', factory1)

// tests are written below

helper.js

import { b } from 'b.js' // Assume b uses 'mockedModule'

jest.mock('mockedModule',factory2)

// helpers are written below

When executing tests from test.js, the process follows the below order.

Here, which factory is used for 'mockedModule' in b depends on whether a imports/requires mockedModule.

Hence, when jest.mock spans multiple files, the content of the mock can vary depending on the internal implementation of the modules being imported.

This feature request seeks to address this by promoting clear guidelines on CLI when detecting this situation.

Pitch

It's about Jest and Jest can notice it efficiently.

github-actions[bot] commented 1 week ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.