Skip to main content

avoid-misused-test-matchers

added in: 1.12.0
Pro+
preset: recommended

Warns when an incorrect matcher or literal is used to verify the target expression.

Using incorrect matchers can lead to unexpected results (a test case passing instead of failing) or redundant checks that can be removed.

info

This rule supports only matchers provided by the test package.

List of supported matchers
  • isNot
  • allOf
  • anyOf
  • isEmpty
  • isNotEmpty
  • isNull
  • isNotNull
  • isTrue
  • isFalse
  • returnsNormally
  • prints
  • isMap
  • isList
  • hasLength
  • contains
  • isIn
  • equals
  • everyElement
  • anyElement
  • orderedEquals
  • unorderedEquals
  • unorderedMatches
  • pairwiseCompare
  • containsAll
  • containsAllInOrder
  • containsOnce
  • containsValue
  • containsPair
  • closeTo
  • inInclusiveRange
  • inExclusiveRange
  • inOpenClosedRange
  • inClosedOpenRange
  • isZero
  • isNonZero
  • isPositive
  • isNonPositive
  • isNegative
  • isNonNegative
  • greaterThan
  • greaterThanOrEqualTo
  • lessThan
  • lessThanOrEqualTo
  • equalsIgnoringCase
  • equalsIgnoringWhitespace
  • startsWith
  • endsWith
  • stringContainsInOrder
  • matches
  • isA
  • completes
  • doesNotComplete
  • emitsDone
  • emits
  • emitsError
  • mayEmit
  • emitsAnyOf
  • emitsInOrder
  • emitsThrough
  • mayEmitMultiple
  • neverEmits
  • emitsInAnyOrder
  • throwsA
  • throwsException
  • throwsStateError
  • throwsUnimplementedError

Example

❌ Bad:

const _someNumber = 1;
const _someString = '1';
const _someList = [1, 2, 3];

void fn() {
expect(_someString, isList); // LINT: Target expression is not a 'List'. Try changing the expression or using a different matcher.
expect({1}, isList); // LINT: Target expression is not a 'List'. Try changing the expression or using a different matcher.
expect(_someNumber, isEmpty); // LINT: Target expression does not have a property named 'isEmpty'. Try changing the expression or using a different matcher.
expect(_someNumber, isNull); // LINT: Target expression can not be null. Try changing the expression or using a different matcher.
expect(_someNumber, isNotNull); // LINT: Target expression is always not null. Try changing the expression or using a different matcher.
expect(_someNumber, hasLength(1)); // LINT: Target expression does not have a property named 'length'. Try changing the expression or using a different matcher.
}

✅ Good:

const _someNumber = 1;
const _someString = '1';
const _someList = [1, 2, 3];

void fn() {
expect(_someString, isA<String>); // Correct, '_someString' is a String
expect(_someList, isList); // Correct, '_someList' is a List
expect(_someNumber, isZero); // Correct, '_someNumber' can be zero
expect(_someList, hasLength(1));
expect(_someList, contains(1));
}