Skip to content

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

@nicolasgillot

Description

@nicolasgillot

Problem

Developers often use toHaveBeenCalledWith() without verifying the call count, leading to tests that pass when a mock is called multiple times unexpectedly.

Solution

Require toHaveBeenCalledTimes() when using toHaveBeenCalledWith() to ensure complete mock validation.

Examples

// ❌ Potentially flaky - passes if called 1 + times
expect(mockFn).toHaveBeenCalledWith(expectedArg)

// ✅ Explicit and safe - ensures exact call count
expect(mockFn).toHaveBeenCalledTimes(1)
expect(mockFn).toHaveBeenCalledWith(expectedArg)

Benefits

  • Prevents false positives in tests
  • Makes test intentions explicit
  • Improves test reliability and maintainability
  • Follows testing best practices

Are you willing to implement this rule? Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions