File size: 1,530 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import { diff } from 'jest-diff';
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention
interface Matchers<R> {
toWarnDev(expectedMessage?: string): jest.CustomMatcherResult;
}
}
}
export const toWarnDev: jest.CustomMatcher = (
callback: () => void,
expectedMessage: string
) => {
if (expectedMessage !== undefined && typeof expectedMessage !== 'string') {
throw new Error(
`toWarnDev() requires a parameter of type string but was given ${typeof expectedMessage}.`
);
}
if (!__DEV__) {
callback();
return { pass: true, message: () => '' };
}
const originalWarnMethod = console.warn;
let calledTimes = 0;
let actualWarning = '';
console.warn = (message: string) => {
calledTimes++;
actualWarning = message;
};
callback();
console.warn = originalWarnMethod;
// Expectation without any message.
// We only check that `console.warn` was called.
if (expectedMessage === undefined && calledTimes === 0) {
return {
pass: false,
message: () => 'No warning recorded.',
};
}
// Expectation with a message.
if (expectedMessage !== undefined && actualWarning !== expectedMessage) {
return {
pass: false,
message: () => `Unexpected warning recorded.
Difference:
${diff(expectedMessage, actualWarning)}`,
};
}
return { pass: true, message: () => '' };
};
|