oxc-project/oxc · warning

Suggest using `toHaveLength()`.

Error message

Suggest using `toHaveLength()`.

What it means

Warning from the oxlint `jest/prefer-to-have-length` rule (source: crates/oxc_linter/src/rules/shared/jest_vitest/prefer_to_have_length.rs:14). It fires when `toBe()`, `toEqual()`, or `toStrictEqual()` is used to assert an object's `length` property, and recommends `toHaveLength()`, whose failure output prints both the received value and its length.

Source

Thrown at crates/oxc_linter/src/rules/shared/jest_vitest/prefer_to_have_length.rs:14

use oxc_ast::{
    AstKind,
    ast::{CallExpression, Expression, MemberExpression, match_member_expression},
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{GetSpan, Span};

use crate::{
    context::LintContext,
    utils::{ParsedExpectFnCall, PossibleJestNode, is_equality_matcher, parse_expect_jest_fn_call},
};

fn use_to_have_length(span: Span) -> OxcDiagnostic {
    OxcDiagnostic::warn("Suggest using `toHaveLength()`.").with_label(span)
}

pub const DOCUMENTATION: &str = r#"### What it does

In order to have a better failure message, `toHaveLength()` should be used upon
asserting expectations on objects length property.

### Why is this bad?

This rule triggers a warning if `toBe()`, `toEqual()` or `toStrictEqual()` is
used to assert objects length property.

### Examples

Examples of **incorrect** code for this rule:
```javascript
expect(files["length"]).toBe(1);
expect(files["length"]).toBe(1,);

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Move the object into `expect` and use the matcher: `expect(arr).toHaveLength(3)`.
  2. For empty checks prefer the clearer `expect(arr).toHaveLength(0)` (or `expect(arr).toBeEmpty()` with jest-extended if configured).
  3. Suppress inline with `// oxlint-disable-next-line jest/prefer-to-have-length` when the length value itself is what is under test.

Example fix

// before
expect(results.length).toBe(3);

// after
expect(results).toHaveLength(3);
Defensive patterns

Strategy: validation

Validate before calling

// rg -n "\.length\)\.(toBe|toEqual|toStrictEqual)\(" tests/ -t ts -t js

Prevention

When it happens

Trigger: `expect(arr.length).toBe(3)`, `expect(str.length).toEqual(0)`, `expect(container.children.length).toStrictEqual(2)` - the expect argument is a `.length` member expression and the matcher is an equality matcher (checked via `is_equality_matcher` in the source).

Common situations: Size assertions on arrays, strings, query results, or DOM children written in the natural `.length` style; suites newly covered by the jest plugin preset; ported code from teams with different matcher conventions.

Related errors


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/13106d928fae3d2b. Report an issue: GitHub.