| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| const util = require('util') |
| const chalk = require('chalk') |
| const shouldIgnoreConsoleError = require('./shouldIgnoreConsoleError') |
|
|
| const patchConsoleMethod = (methodName, unexpectedConsoleCallStacks) => { |
| const newMethod = function (format, ...args) { |
| |
| |
| if (methodName === 'error' && shouldIgnoreConsoleError(format, args)) { |
| return |
| } |
|
|
| |
| |
| |
| const stack = new Error().stack |
| unexpectedConsoleCallStacks.push([ |
| stack.substr(stack.indexOf('\n') + 1), |
| util.format(format, ...args), |
| ]) |
| } |
|
|
| console[methodName] = newMethod |
|
|
| return newMethod |
| } |
|
|
| const isSpy = spy => |
| (spy.calls && typeof spy.calls.count === 'function') || |
| spy._isMockFunction === true |
|
|
| const flushUnexpectedConsoleCalls = ( |
| mockMethod, |
| methodName, |
| expectedMatcher, |
| unexpectedConsoleCallStacks, |
| ) => { |
| if (console[methodName] !== mockMethod && !isSpy(console[methodName])) { |
| throw new Error( |
| `Test did not tear down console.${methodName} mock properly.`, |
| ) |
| } |
| if (unexpectedConsoleCallStacks.length > 0) { |
| const messages = unexpectedConsoleCallStacks.map( |
| ([stack, message]) => |
| `${chalk.red(message)}\n` + |
| `${stack |
| .split('\n') |
| .map(line => chalk.gray(line)) |
| .join('\n')}`, |
| ) |
|
|
| const message = |
| `Expected test not to call ${chalk.bold( |
| `console.${methodName}()`, |
| )}.\n\n` + |
| 'If the warning is expected, test for it explicitly by:\n' + |
| `1. Using the ${chalk.bold('.' + expectedMatcher + '()')} ` + |
| `matcher, or...\n` + |
| `2. Mock it out using ${chalk.bold( |
| 'spyOnDev', |
| )}(console, '${methodName}') or ${chalk.bold( |
| 'spyOnProd', |
| )}(console, '${methodName}'), and test that the warning occurs.` |
|
|
| throw new Error(`${message}\n\n${messages.join('\n\n')}`) |
| } |
| } |
|
|
| const unexpectedErrorCallStacks = [] |
| const unexpectedWarnCallStacks = [] |
|
|
| const errorMethod = patchConsoleMethod('error', unexpectedErrorCallStacks) |
| const warnMethod = patchConsoleMethod('warn', unexpectedWarnCallStacks) |
|
|
| const flushAllUnexpectedConsoleCalls = () => { |
| flushUnexpectedConsoleCalls( |
| errorMethod, |
| 'error', |
| 'toErrorDev', |
| unexpectedErrorCallStacks, |
| ) |
| flushUnexpectedConsoleCalls( |
| warnMethod, |
| 'warn', |
| 'toWarnDev', |
| unexpectedWarnCallStacks, |
| ) |
| unexpectedErrorCallStacks.length = 0 |
| unexpectedWarnCallStacks.length = 0 |
| } |
|
|
| const resetAllUnexpectedConsoleCalls = () => { |
| unexpectedErrorCallStacks.length = 0 |
| unexpectedWarnCallStacks.length = 0 |
| } |
|
|
| expect.extend({ |
| ...require('./toWarnDev'), |
| }) |
|
|
| beforeEach(resetAllUnexpectedConsoleCalls) |
| afterEach(flushAllUnexpectedConsoleCalls) |
|
|