Skip to content

useExpectToHaveBeenCalledTimes (JavaScript)

Language JavaScript (and super languages)
biome.json
{
"linter": {
"rules": {
"nursery": {
"useExpectToHaveBeenCalledTimes": "error"
}
}
}
}

Enforce using toHaveBeenCalledTimes() to check how many times a mock function was called.

A mock function is a replacement for a real function that a test framework creates, for example with jest.fn() or vi.fn(). It records every call it receives in its mock.calls array.

Checking the length of that array with toHaveLength() works, but when the test fails, the error message describes the length of an array. toHaveBeenCalledTimes() reports the expected and received number of calls, which makes failures easier to understand.

The fix is unsafe because toHaveBeenCalledTimes() only accepts mock functions. A value that isn’t a mock function but has its own mock.calls array passes toHaveLength() and fails toHaveBeenCalledTimes().

expect(onSave.mock.calls).toHaveLength(1);
code-block.js:1:27 lint/nursery/useExpectToHaveBeenCalledTimes  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ toHaveLength() is used to check how many times a mock function was called.

> 1 │ expect(onSave.mock.calls).toHaveLength(1);
│ ^^^^^^^^^^^^
2 │

ℹ When this check fails, the error message describes the length of an array instead of the number of calls.

ℹ Use toHaveBeenCalledTimes() to check the number of calls.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

ℹ Unsafe fix: Use toHaveBeenCalledTimes() instead.

1 │ - expect(onSave.mock.calls).toHaveLength(1);
1 │ + expect(onSave).toHaveBeenCalledTimes(1);
2 2 │

expect(onSave.mock.calls).not.toHaveLength(0);
code-block.js:1:31 lint/nursery/useExpectToHaveBeenCalledTimes  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ toHaveLength() is used to check how many times a mock function was called.

> 1 │ expect(onSave.mock.calls).not.toHaveLength(0);
│ ^^^^^^^^^^^^
2 │

ℹ When this check fails, the error message describes the length of an array instead of the number of calls.

ℹ Use toHaveBeenCalledTimes() to check the number of calls.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

ℹ Unsafe fix: Use toHaveBeenCalledTimes() instead.

1 │ - expect(onSave.mock.calls).not.toHaveLength(0);
1 │ + expect(onSave).not.toHaveBeenCalledTimes(0);
2 2 │

expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).not.toHaveBeenCalledTimes(0);
expect(onSave.mock.calls[0]).toHaveLength(2);