in packages/expect/src/matchers.ts [794:870]
toMatch(received: string, expected: string | RegExp) {
const matcherName = 'toMatch';
const options: MatcherHintOptions = {
isNot: this.isNot,
promise: this.promise,
};
if (typeof received !== 'string') {
throw new Error(
matcherErrorMessage(
matcherHint(matcherName, undefined, undefined, options),
`${RECEIVED_COLOR('received')} value must be a string`,
printWithType('Received', received, printReceived),
),
);
}
if (
!(typeof expected === 'string') &&
!(expected && typeof expected.test === 'function')
) {
throw new Error(
matcherErrorMessage(
matcherHint(matcherName, undefined, undefined, options),
`${EXPECTED_COLOR(
'expected',
)} value must be a string or regular expression`,
printWithType('Expected', expected, printExpected),
),
);
}
const pass =
typeof expected === 'string'
? received.includes(expected)
: new RegExp(expected).test(received);
const message = pass
? () =>
typeof expected === 'string'
? // eslint-disable-next-line prefer-template
matcherHint(matcherName, undefined, undefined, options) +
'\n\n' +
`Expected substring: not ${printExpected(expected)}\n` +
`Received string: ${printReceivedStringContainExpectedSubstring(
received,
received.indexOf(expected),
expected.length,
)}`
: // eslint-disable-next-line prefer-template
matcherHint(matcherName, undefined, undefined, options) +
'\n\n' +
`Expected pattern: not ${printExpected(expected)}\n` +
`Received string: ${printReceivedStringContainExpectedResult(
received,
typeof expected.exec === 'function'
? expected.exec(received)
: null,
)}`
: () => {
const labelExpected = `Expected ${
typeof expected === 'string' ? 'substring' : 'pattern'
}`;
const labelReceived = 'Received string';
const printLabel = getLabelPrinter(labelExpected, labelReceived);
return (
// eslint-disable-next-line prefer-template
matcherHint(matcherName, undefined, undefined, options) +
'\n\n' +
`${printLabel(labelExpected)}${printExpected(expected)}\n` +
`${printLabel(labelReceived)}${printReceived(received)}`
);
};
return {message, pass};
},