Skip to content

toHaveLengthMatchers

Reports equality matchers on .length that could use toHaveLength().

✅ This rule is included in the vitest stylistic and stylisticStrict presets.

Vitest’s toHaveLength() matcher asserts on the .length property of the value passed to expect(). Reading .length yourself and comparing it with toBe(), toEqual(), or toStrictEqual() checks the same thing, but a failure only prints the two numbers, such as expected 3 to be 2. A failing toHaveLength() also prints the received value, such as expected [ 'a.ts', 'b.ts', 'c.ts' ] to have a length of 2 but got 3.

This rule does not report .length accesses inside an optional chain, such as expect(files?.length).toBe(1). toHaveLength() throws an error when the received value is undefined, so it is not equivalent there.

expect(files.length).toBe(1);
expect(files.length).toEqual(1);
expect(files.length).toStrictEqual(1);
expect(files.length).not.toBe(0);

This rule is not configurable.

If your tests compare .length against an asymmetric matcher, such as expect(files.length).toEqual(expect.any(Number)), this rule’s fix changes the result of the assertion, because toHaveLength() only accepts a number.