const chalk = require('chalk');
const util = require('util');
const shouldIgnoreConsoleError = require('./shouldIgnoreConsoleError');
const shouldIgnoreConsoleWarn = require('./shouldIgnoreConsoleWarn');
import {diff} from 'jest-diff';
import {printReceived} from 'jest-matcher-utils';
const loggedErrors = (global.__loggedErrors = global.__loggedErrors || []);
const loggedWarns = (global.__loggedWarns = global.__loggedWarns || []);
const loggedLogs = (global.__loggedLogs = global.__loggedLogs || []);
const patchConsoleMethod = (methodName, logged) => {
const newMethod = function (format, ...args) {
if (shouldIgnoreConsoleError(format, args)) {
return;
}
if (methodName === 'warn' && shouldIgnoreConsoleWarn(format)) {
return;
}
if (
typeof format === 'string' &&
(methodName === 'error' || methodName === 'warn')
) {
const React = require('react');
if (React.captureOwnerStack) {
const stack = React.captureOwnerStack();
if (stack) {
format += '%s';
args.push(stack);
}
}
}
logged.push([format, ...args]);
};
console[methodName] = newMethod;
return newMethod;
};
let logMethod;
export function patchConsoleMethods({includeLog} = {includeLog: false}) {
patchConsoleMethod('error', loggedErrors);
patchConsoleMethod('warn', loggedWarns);
if (includeLog) {
logMethod = patchConsoleMethod('log', loggedLogs);
}
}
export function resetAllUnexpectedConsoleCalls() {
loggedErrors.length = 0;
loggedWarns.length = 0;
if (logMethod) {
loggedLogs.length = 0;
}
}
export function clearLogs() {
const logs = Array.from(loggedLogs);
loggedLogs.length = 0;
return logs;
}
export function clearWarnings() {
const warnings = Array.from(loggedWarns);
loggedWarns.length = 0;
return warnings;
}
export function clearErrors() {
const errors = Array.from(loggedErrors);
loggedErrors.length = 0;
return errors;
}
export function assertConsoleLogsCleared() {
const logs = clearLogs();
const warnings = clearWarnings();
const errors = clearErrors();
if (logs.length > 0 || errors.length > 0 || warnings.length > 0) {
let message = `${chalk.dim('asserConsoleLogsCleared')}(${chalk.red(
'expected',
)})\n`;
if (logs.length > 0) {
message += `\nconsole.log was called without assertConsoleLogDev:\n${diff(
'',
logs.join('\n'),
{
omitAnnotationLines: true,
},
)}\n`;
}
if (warnings.length > 0) {
message += `\nconsole.warn was called without assertConsoleWarnDev:\n${diff(
'',
warnings.map(normalizeComponentStack).join('\n'),
{
omitAnnotationLines: true,
},
)}\n`;
}
if (errors.length > 0) {
message += `\nconsole.error was called without assertConsoleErrorDev:\n${diff(
'',
errors.map(normalizeComponentStack).join('\n'),
{
omitAnnotationLines: true,
},
)}\n`;
}
message += `\nYou must call one of the assertConsoleDev helpers between each act call.`;
const error = Error(message);
Error.captureStackTrace(error, assertConsoleLogsCleared);
throw error;
}
}
function normalizeCodeLocInfo(str) {
if (typeof str !== 'string') {
return str;
}
str = str.replace(/Check your code at .+?:\d+/g, 'Check your code at **');
return str.replace(/\n +(?:at|in) ([^(\[\n]+)[^\n]*/g, function (m, name) {
name = name.trim();
if (name.endsWith('.render')) {
name = name.slice(0, name.length - 7);
}
name = name.replace(/.*\/([^\/]+):\d+:\d+/, '**/$1:**:**');
return '\n in ' + name + ' (at **)';
});
}
function expandEnvironmentPlaceholders(str) {
if (typeof str !== 'string') {
return str;
}
return str.replace(
/^\[(\w+)] /g,
(match, env) => '\u001b[0m\u001b[7m ' + env + ' \u001b[0m',
);
}
const ERROR_STACK_PLACEHOLDER = '\n in <stack>';
const ERROR_STACK_PLACEHOLDER_MARKER = '\n in <__STACK_PLACEHOLDER__>';
function normalizeExpectedMessage(str) {
if (typeof str !== 'string') {
return str;
}
const hasStackPlaceholder = str.includes(ERROR_STACK_PLACEHOLDER);
let result = str;
if (hasStackPlaceholder) {
result = result.replace(
ERROR_STACK_PLACEHOLDER,
ERROR_STACK_PLACEHOLDER_MARKER,
);
}
result = normalizeCodeLocInfo(result);
result = expandEnvironmentPlaceholders(result);
if (hasStackPlaceholder) {
result = result.replace(
ERROR_STACK_PLACEHOLDER_MARKER + ' (at **)',
ERROR_STACK_PLACEHOLDER,
);
}
return result;
}
function normalizeComponentStack(entry) {
if (
typeof entry[0] === 'string' &&
entry[0].endsWith('%s') &&
isLikelyAComponentStack(entry[entry.length - 1])
) {
const clone = entry.slice(0);
clone[clone.length - 1] = normalizeCodeLocInfo(entry[entry.length - 1]);
return clone;
}
return entry;
}
const isLikelyAComponentStack = message =>
typeof message === 'string' &&
(message.indexOf('<component stack>') > -1 ||
message.includes('\n in ') ||
message.includes('\n at '));
const isLikelyAnErrorStackTrace = message =>
typeof message === 'string' &&
message.includes('Error:') &&
/\n\s+at .+\(.*:\d+:\d+\)/.test(message);
export function createLogAssertion(
consoleMethod,
matcherName,
clearObservedErrors,
) {
function logName() {
switch (consoleMethod) {
case 'log':
return 'log';
case 'error':
return 'error';
case 'warn':
return 'warning';
}
}
return function assertConsoleLog(expectedMessages, options = {}) {
if (__DEV__) {
function throwFormattedError(message) {
const error = new Error(
`${chalk.dim(matcherName)}(${chalk.red(
'expected',
)})\n\n${message.trim()}`,
);
Error.captureStackTrace(error, assertConsoleLog);
throw error;
}
if (!Array.isArray(expectedMessages)) {
throwFormattedError(
`Expected messages should be an array of strings ` +
`but was given type "${typeof expectedMessages}".`,
);
}
if (options != null) {
if (typeof options !== 'object' || Array.isArray(options)) {
throwFormattedError(
`The second argument should be an object. ` +
'Did you forget to wrap the messages into an array?',
);
}
}
const observedLogs = clearObservedErrors();
const receivedLogs = [];
const missingExpectedLogs = Array.from(expectedMessages);
const unexpectedLogs = [];
const unexpectedMissingErrorStack = [];
const unexpectedIncludingErrorStack = [];
const logsMismatchingFormat = [];
const logsWithExtraComponentStack = [];
const stackTracePlaceholderMisuses = [];
for (let index = 0; index < observedLogs.length; index++) {
const log = observedLogs[index];
const [format, ...args] = log;
const message = util.format(format, ...args);
if (shouldIgnoreConsoleError(format, args)) {
return;
}
let expectedMessage;
const expectedMessageOrArray = expectedMessages[index];
if (typeof expectedMessageOrArray === 'string') {
expectedMessage = normalizeExpectedMessage(expectedMessageOrArray);
} else if (expectedMessageOrArray != null) {
throwFormattedError(
`The expected message for ${matcherName}() must be a string. ` +
`Instead received ${JSON.stringify(expectedMessageOrArray)}.`,
);
}
const normalizedMessage = normalizeCodeLocInfo(message);
receivedLogs.push(normalizedMessage);
let argIndex = 0;
String(format).replace(/%s|%c|%o/g, () => argIndex++);
if (argIndex !== args.length) {
if (format.includes('%c%s')) {
} else {
logsMismatchingFormat.push({
format,
args,
expectedArgCount: argIndex,
});
}
}
if (
args.length >= 2 &&
isLikelyAComponentStack(args[args.length - 1]) &&
isLikelyAComponentStack(args[args.length - 2])
) {
logsWithExtraComponentStack.push({
format,
});
}
let matchesExpectedMessage = false;
let expectsErrorStack = false;
const hasErrorStack = isLikelyAnErrorStackTrace(message);
if (typeof expectedMessage === 'string') {
if (normalizedMessage === expectedMessage) {
matchesExpectedMessage = true;
} else if (expectedMessage.includes('\n in <stack>')) {
expectsErrorStack = true;
if (!hasErrorStack) {
stackTracePlaceholderMisuses.push({
expected: expectedMessage,
received: normalizedMessage,
});
}
const expectedMessageWithoutStack = expectedMessage.replace(
'\n in <stack>',
'',
);
if (normalizedMessage.startsWith(expectedMessageWithoutStack)) {
const remainder = normalizedMessage.slice(
expectedMessageWithoutStack.length,
);
if (isLikelyAComponentStack(remainder)) {
const messageWithoutStack = normalizedMessage.replace(
remainder,
'',
);
if (messageWithoutStack === expectedMessageWithoutStack) {
matchesExpectedMessage = true;
}
} else if (remainder === '') {
matchesExpectedMessage = true;
}
} else if (normalizedMessage === expectedMessageWithoutStack) {
matchesExpectedMessage = true;
}
} else if (
hasErrorStack &&
!expectedMessage.includes('\n in <stack>') &&
normalizedMessage.startsWith(expectedMessage)
) {
matchesExpectedMessage = true;
}
}
if (matchesExpectedMessage) {
if (hasErrorStack && !expectsErrorStack) {
unexpectedIncludingErrorStack.push(normalizedMessage);
} else if (
expectsErrorStack &&
!hasErrorStack &&
!isLikelyAComponentStack(normalizedMessage)
) {
unexpectedMissingErrorStack.push(normalizedMessage);
}
missingExpectedLogs.splice(0, 1);
} else {
unexpectedLogs.push(normalizedMessage);
}
}
function printDiff() {
return `${diff(
expectedMessages
.map(message => message.replace('\n', ' '))
.join('\n'),
receivedLogs.map(message => message.replace('\n', ' ')).join('\n'),
{
aAnnotation: `Expected ${logName()}s`,
bAnnotation: `Received ${logName()}s`,
},
)}`;
}
if (logsMismatchingFormat.length > 0) {
throwFormattedError(
logsMismatchingFormat
.map(
item =>
`Received ${item.args.length} arguments for a message with ${
item.expectedArgCount
} placeholders:\n ${printReceived(item.format)}`,
)
.join('\n\n'),
);
}
if (unexpectedLogs.length > 0) {
throwFormattedError(
`Unexpected ${logName()}(s) recorded.\n\n${printDiff()}`,
);
}
if (missingExpectedLogs.length > 0) {
throwFormattedError(
`Expected ${logName()} was not recorded.\n\n${printDiff()}`,
);
}
if (unexpectedIncludingErrorStack.length > 0) {
throwFormattedError(
`${unexpectedIncludingErrorStack
.map(
stack =>
`Unexpected error stack trace for:\n ${printReceived(stack)}`,
)
.join(
'\n\n',
)}\n\nIf this ${logName()} should include an error stack trace, add \\n in <stack> to your expected message ` +
`(e.g., "Error: message\\n in <stack>").`,
);
}
if (unexpectedMissingErrorStack.length > 0) {
throwFormattedError(
`${unexpectedMissingErrorStack
.map(
stack =>
`Missing error stack trace for:\n ${printReceived(stack)}`,
)
.join(
'\n\n',
)}\n\nThe expected message uses \\n in <stack> but the actual ${logName()} doesn't include an error stack trace.` +
`\nIf this ${logName()} should not have an error stack trace, remove \\n in <stack> from your expected message.`,
);
}
if (logsWithExtraComponentStack.length > 0) {
throwFormattedError(
logsWithExtraComponentStack
.map(
item =>
`Received more than one component stack for a warning:\n ${printReceived(
item.format,
)}`,
)
.join('\n\n'),
);
}
if (stackTracePlaceholderMisuses.length > 0) {
throwFormattedError(
`${stackTracePlaceholderMisuses
.map(
item =>
`Incorrect use of \\n in <stack> placeholder. The placeholder is for JavaScript Error ` +
`stack traces (messages starting with "Error:"), not for React component stacks.\n\n` +
`Expected: ${printReceived(item.expected)}\n` +
`Received: ${printReceived(item.received)}\n\n` +
`If this ${logName()} has a component stack, include the full component stack in your expected message ` +
`(e.g., "Warning message\\n in ComponentName (at **)").`,
)
.join('\n\n')}`,
);
}
}
};
}