|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const jestDiff = require('jest-diff').default; |
| 4 | +const util = require('util'); |
| 5 | +const shouldIgnoreConsoleError = require('../shouldIgnoreConsoleError'); |
| 6 | + |
| 7 | +function normalizeCodeLocInfo(str) { |
| 8 | + return str && str.replace(/at .+?:\d+/g, 'at **'); |
| 9 | +} |
| 10 | + |
| 11 | +const createMatcherFor = (consoleMethod, matcherName) => |
| 12 | + function matcher(callback, expectedMessages, options = {}) { |
| 13 | + if (process.env.NODE_ENV !== 'production') { |
| 14 | + // Warn about incorrect usage of matcher. |
| 15 | + if (typeof expectedMessages === 'string') { |
| 16 | + expectedMessages = [expectedMessages]; |
| 17 | + } else if (!Array.isArray(expectedMessages)) { |
| 18 | + throw Error( |
| 19 | + `${matcherName}() requires a parameter of type string or an array of strings ` + |
| 20 | + `but was given ${typeof expectedMessages}.`, |
| 21 | + ); |
| 22 | + } |
| 23 | + if ( |
| 24 | + options != null && |
| 25 | + (typeof options !== 'object' || Array.isArray(options)) |
| 26 | + ) { |
| 27 | + throw new Error( |
| 28 | + `${matcherName}() second argument, when present, should be an object. ` + |
| 29 | + 'Did you forget to wrap the messages into an array?', |
| 30 | + ); |
| 31 | + } |
| 32 | + if (arguments.length > 3) { |
| 33 | + // `matcher` comes from Jest, so it's more than 2 in practice |
| 34 | + throw new Error( |
| 35 | + `${matcherName}() received more than two arguments. ` + |
| 36 | + 'Did you forget to wrap the messages into an array?', |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + const withoutStack = options.withoutStack; |
| 41 | + const logAllErrors = options.logAllErrors; |
| 42 | + const warningsWithoutComponentStack = []; |
| 43 | + const warningsWithComponentStack = []; |
| 44 | + const unexpectedWarnings = []; |
| 45 | + |
| 46 | + let lastWarningWithMismatchingFormat = null; |
| 47 | + let lastWarningWithExtraComponentStack = null; |
| 48 | + |
| 49 | + // Catch errors thrown by the callback, |
| 50 | + // But only rethrow them if all test expectations have been satisfied. |
| 51 | + // Otherwise an Error in the callback can mask a failed expectation, |
| 52 | + // and result in a test that passes when it shouldn't. |
| 53 | + let caughtError; |
| 54 | + |
| 55 | + const isLikelyAComponentStack = message => |
| 56 | + typeof message === 'string' && message.includes('\n in '); |
| 57 | + |
| 58 | + const consoleSpy = (format, ...args) => { |
| 59 | + // Ignore uncaught errors reported by jsdom |
| 60 | + // and React addendums because they're too noisy. |
| 61 | + if ( |
| 62 | + !logAllErrors && |
| 63 | + consoleMethod === 'error' && |
| 64 | + shouldIgnoreConsoleError(format, args) |
| 65 | + ) { |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const message = util.format(format, ...args); |
| 70 | + const normalizedMessage = normalizeCodeLocInfo(message); |
| 71 | + |
| 72 | + // Remember if the number of %s interpolations |
| 73 | + // doesn't match the number of arguments. |
| 74 | + // We'll fail the test if it happens. |
| 75 | + let argIndex = 0; |
| 76 | + format.replace(/%s/g, () => argIndex++); |
| 77 | + if (argIndex !== args.length) { |
| 78 | + lastWarningWithMismatchingFormat = { |
| 79 | + format, |
| 80 | + args, |
| 81 | + expectedArgCount: argIndex, |
| 82 | + }; |
| 83 | + } |
| 84 | + |
| 85 | + // Protect against accidentally passing a component stack |
| 86 | + // to warning() which already injects the component stack. |
| 87 | + if ( |
| 88 | + args.length >= 2 && |
| 89 | + isLikelyAComponentStack(args[args.length - 1]) && |
| 90 | + isLikelyAComponentStack(args[args.length - 2]) |
| 91 | + ) { |
| 92 | + lastWarningWithExtraComponentStack = { |
| 93 | + format, |
| 94 | + }; |
| 95 | + } |
| 96 | + |
| 97 | + for (let index = 0; index < expectedMessages.length; index++) { |
| 98 | + const expectedMessage = expectedMessages[index]; |
| 99 | + if ( |
| 100 | + normalizedMessage === expectedMessage || |
| 101 | + normalizedMessage.includes(expectedMessage) |
| 102 | + ) { |
| 103 | + if (isLikelyAComponentStack(normalizedMessage)) { |
| 104 | + warningsWithComponentStack.push(normalizedMessage); |
| 105 | + } else { |
| 106 | + warningsWithoutComponentStack.push(normalizedMessage); |
| 107 | + } |
| 108 | + expectedMessages.splice(index, 1); |
| 109 | + return; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + let errorMessage; |
| 114 | + if (expectedMessages.length === 0) { |
| 115 | + errorMessage = |
| 116 | + 'Unexpected warning recorded: ' + |
| 117 | + this.utils.printReceived(normalizedMessage); |
| 118 | + } else if (expectedMessages.length === 1) { |
| 119 | + errorMessage = |
| 120 | + 'Unexpected warning recorded: ' + |
| 121 | + jestDiff(expectedMessages[0], normalizedMessage); |
| 122 | + } else { |
| 123 | + errorMessage = |
| 124 | + 'Unexpected warning recorded: ' + |
| 125 | + jestDiff(expectedMessages, [normalizedMessage]); |
| 126 | + } |
| 127 | + |
| 128 | + // Record the call stack for unexpected warnings. |
| 129 | + // We don't throw an Error here though, |
| 130 | + // Because it might be suppressed by ReactFiberScheduler. |
| 131 | + unexpectedWarnings.push(new Error(errorMessage)); |
| 132 | + }; |
| 133 | + |
| 134 | + // TODO Decide whether we need to support nested toWarn* expectations. |
| 135 | + // If we don't need it, add a check here to see if this is already our spy, |
| 136 | + // And throw an error. |
| 137 | + const originalMethod = console[consoleMethod]; |
| 138 | + |
| 139 | + // Avoid using Jest's built-in spy since it can't be removed. |
| 140 | + console[consoleMethod] = consoleSpy; |
| 141 | + |
| 142 | + try { |
| 143 | + callback(); |
| 144 | + } catch (error) { |
| 145 | + caughtError = error; |
| 146 | + } finally { |
| 147 | + // Restore the unspied method so that unexpected errors fail tests. |
| 148 | + console[consoleMethod] = originalMethod; |
| 149 | + |
| 150 | + // Any unexpected Errors thrown by the callback should fail the test. |
| 151 | + // This should take precedence since unexpected errors could block warnings. |
| 152 | + if (caughtError) { |
| 153 | + throw caughtError; |
| 154 | + } |
| 155 | + |
| 156 | + // Any unexpected warnings should be treated as a failure. |
| 157 | + if (unexpectedWarnings.length > 0) { |
| 158 | + return { |
| 159 | + message: () => unexpectedWarnings[0].stack, |
| 160 | + pass: false, |
| 161 | + }; |
| 162 | + } |
| 163 | + |
| 164 | + // Any remaining messages indicate a failed expectations. |
| 165 | + if (expectedMessages.length > 0) { |
| 166 | + return { |
| 167 | + message: () => |
| 168 | + `Expected warning was not recorded:\n ${this.utils.printReceived( |
| 169 | + expectedMessages[0], |
| 170 | + )}`, |
| 171 | + pass: false, |
| 172 | + }; |
| 173 | + } |
| 174 | + |
| 175 | + if (typeof withoutStack === 'number') { |
| 176 | + // We're expecting a particular number of warnings without stacks. |
| 177 | + if (withoutStack !== warningsWithoutComponentStack.length) { |
| 178 | + return { |
| 179 | + message: () => |
| 180 | + `Expected ${withoutStack} warnings without a component stack but received ${warningsWithoutComponentStack.length}:\n` + |
| 181 | + warningsWithoutComponentStack.map(warning => |
| 182 | + this.utils.printReceived(warning), |
| 183 | + ), |
| 184 | + pass: false, |
| 185 | + }; |
| 186 | + } |
| 187 | + } else if (withoutStack === true) { |
| 188 | + // We're expecting that all warnings won't have the stack. |
| 189 | + // If some warnings have it, it's an error. |
| 190 | + if (warningsWithComponentStack.length > 0) { |
| 191 | + return { |
| 192 | + message: () => |
| 193 | + `Received warning unexpectedly includes a component stack:\n ${this.utils.printReceived( |
| 194 | + warningsWithComponentStack[0], |
| 195 | + )}\nIf this warning intentionally includes the component stack, remove ` + |
| 196 | + `{withoutStack: true} from the ${matcherName}() call. If you have a mix of ` + |
| 197 | + `warnings with and without stack in one ${matcherName}() call, pass ` + |
| 198 | + `{withoutStack: N} where N is the number of warnings without stacks.`, |
| 199 | + pass: false, |
| 200 | + }; |
| 201 | + } |
| 202 | + } else if (withoutStack === false || withoutStack === undefined) { |
| 203 | + // We're expecting that all warnings *do* have the stack (default). |
| 204 | + // If some warnings don't have it, it's an error. |
| 205 | + if (warningsWithoutComponentStack.length > 0) { |
| 206 | + return { |
| 207 | + message: () => |
| 208 | + `Received warning unexpectedly does not include a component stack:\n ${this.utils.printReceived( |
| 209 | + warningsWithoutComponentStack[0], |
| 210 | + )}\nIf this warning intentionally omits the component stack, add ` + |
| 211 | + `{withoutStack: true} to the ${matcherName} call.`, |
| 212 | + pass: false, |
| 213 | + }; |
| 214 | + } |
| 215 | + } else { |
| 216 | + throw Error( |
| 217 | + `The second argument for ${matcherName}(), when specified, must be an object. It may have a ` + |
| 218 | + `property called "withoutStack" whose value may be undefined, boolean, or a number. ` + |
| 219 | + `Instead received ${typeof withoutStack}.`, |
| 220 | + ); |
| 221 | + } |
| 222 | + |
| 223 | + if (lastWarningWithMismatchingFormat !== null) { |
| 224 | + return { |
| 225 | + message: () => |
| 226 | + `Received ${ |
| 227 | + lastWarningWithMismatchingFormat.args.length |
| 228 | + } arguments for a message with ${ |
| 229 | + lastWarningWithMismatchingFormat.expectedArgCount |
| 230 | + } placeholders:\n ${this.utils.printReceived( |
| 231 | + lastWarningWithMismatchingFormat.format, |
| 232 | + )}`, |
| 233 | + pass: false, |
| 234 | + }; |
| 235 | + } |
| 236 | + |
| 237 | + if (lastWarningWithExtraComponentStack !== null) { |
| 238 | + return { |
| 239 | + message: () => |
| 240 | + `Received more than one component stack for a warning:\n ${this.utils.printReceived( |
| 241 | + lastWarningWithExtraComponentStack.format, |
| 242 | + )}\nDid you accidentally pass a stack to warning() as the last argument? ` + |
| 243 | + `Don't forget warning() already injects the component stack automatically.`, |
| 244 | + pass: false, |
| 245 | + }; |
| 246 | + } |
| 247 | + |
| 248 | + return {pass: true}; |
| 249 | + } |
| 250 | + } else { |
| 251 | + // Any uncaught errors or warnings should fail tests in production mode. |
| 252 | + callback(); |
| 253 | + |
| 254 | + return {pass: true}; |
| 255 | + } |
| 256 | + }; |
| 257 | + |
| 258 | +module.exports = { |
| 259 | + toWarnDev: createMatcherFor('warn', 'toWarnDev'), |
| 260 | + toErrorDev: createMatcherFor('error', 'toErrorDev'), |
| 261 | +}; |
0 commit comments