Skip to content

Conversation

@nicolasgillot
Copy link

@nicolasgillot nicolasgillot commented Nov 12, 2025

Summary

This PR introduces a new ESLint rule pair-to-have-been-called-assertions that enforces using toHaveBeenCalledTimes() or toBeCalledTimes() whenever using matchers like toHaveBeenCalledWith(), toBeCalledWith(), toHaveBeenNthCalledWith(), toBeNthCalledWith(), toHaveBeenLastCalledWith(), or toBeLastCalledWith().

Why?

When testing mock functions, developers often use toHaveBeenCalledWith() to verify that a function was called with specific arguments. However, without also checking the call count, the test can pass even if the mock was called more times than expected, potentially masking bugs.

What does this rule do?

  • Requires pairing toHaveBeenCalledWith() (and similar matchers) with toHaveBeenCalledTimes()
  • Provides auto-fix that adds the missing toHaveBeenCalledTimes(1) assertion
  • Detects contradictory assertions (e.g., toHaveBeenCalledTimes(0) with toHaveBeenCalledWith())
  • Works with all call-checking matchers: toHaveBeenCalledWith, toBeCalledWith, toHaveBeenNthCalledWith, toBeNthCalledWith, toHaveBeenLastCalledWith, toBeLastCalledWith

Examples

❌ Incorrect:

expect(mockFn).toHaveBeenCalledWith('arg');

✅ Correct:

expect(mockFn).toHaveBeenCalledTimes(1);
expect(mockFn).toHaveBeenCalledWith('arg');

Resolves #1820

@nicolasgillot nicolasgillot force-pushed the pair-to-have-been-called-assertions branch from 0f96239 to ce3724f Compare November 12, 2025 16:24
@nicolasgillot nicolasgillot force-pushed the pair-to-have-been-called-assertions branch from ce3724f to dd0b9b3 Compare November 12, 2025 16:28
@G-Rath G-Rath changed the title feat: create new pair-to-have-been-called-assertions rule feat: create new pair-to-have-been-called-assertions rule Nov 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rule proposal: jest/prefer-strict-mock-assertions

1 participant