toHaveLengthMatchers
Reports equality matchers on
.lengththat could usetoHaveLength().
✅ This rule is included in the viteststylisticandstylisticStrictpresets.
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.
Examples
Section titled “Examples”expect(files.length).toBe(1);expect(files.length).toEqual(1);expect(files.length).toStrictEqual(1);expect(files.length).not.toBe(0);expect(files).toHaveLength(1);expect(files).not.toHaveLength(0);expect(files.length).toBeGreaterThan(1);expect(files?.length).toBe(1);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
vitest/prefer-to-have-length - Oxlint:
vitest/prefer-to-have-length
