From 05d550577abb065c6f8ea73ba6b901ccdbd7ca24 Mon Sep 17 00:00:00 2001 From: Mark Erikson Date: Fri, 2 Apr 2021 17:14:15 -0400 Subject: [PATCH 1/4] Port error extraction setup from master --- errors.json | 18 ++++ rollup.config.js | 5 + scripts/mangleErrors.js | 151 ++++++++++++++++++++++++++++ src/createStore.js | 4 +- src/utils/formatProdErrorMessage.js | 15 +++ 5 files changed, 191 insertions(+), 2 deletions(-) create mode 100644 errors.json create mode 100644 scripts/mangleErrors.js create mode 100644 src/utils/formatProdErrorMessage.js diff --git a/errors.json b/errors.json new file mode 100644 index 0000000000..4c605cd2c1 --- /dev/null +++ b/errors.json @@ -0,0 +1,18 @@ +{ + "0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.", + "1": "Expected the enhancer to be a function.", + "2": "Expected the reducer to be a function.", + "3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.", + "4": "Expected the listener to be a function.", + "5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.", + "6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.", + "7": "Actions must be plain objects. Use custom middleware for async actions.", + "8": "Actions may not have an undefined \"type\" property. Have you misspelled a constant?", + "9": "Reducers may not dispatch actions.", + "10": "Expected the nextReducer to be a function.", + "11": "Expected the observer to be an object.", + "12": "bindActionCreators expected an object or a function, instead received . Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?", + "13": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.", + "14": "Reducer \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.", + "15": "Reducer \"\" returned undefined when probed with a random type. Don't try to handle or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null." +} \ No newline at end of file diff --git a/rollup.config.js b/rollup.config.js index 9a32e51479..90af2fd2be 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -37,6 +37,7 @@ export default [ extensions, plugins: [ ['@babel/plugin-transform-runtime', { version: babelRuntimeVersion }], + ['./scripts/mangleErrors.js', { minify: false }] ], babelHelpers: 'runtime' }) @@ -62,6 +63,7 @@ export default [ '@babel/plugin-transform-runtime', { version: babelRuntimeVersion, useESModules: true } ], + ['./scripts/mangleErrors.js', { minify: false }] ], babelHelpers: 'runtime' }) @@ -82,6 +84,7 @@ export default [ babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: true }]], skipPreflightCheck: true }), terser({ @@ -111,6 +114,7 @@ export default [ babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: false }]] }), replace({ 'process.env.NODE_ENV': JSON.stringify('development') @@ -134,6 +138,7 @@ export default [ babel({ extensions, exclude: 'node_modules/**', + plugins: [['./scripts/mangleErrors.js', { minify: true }]], skipPreflightCheck: true }), replace({ diff --git a/scripts/mangleErrors.js b/scripts/mangleErrors.js new file mode 100644 index 0000000000..2c4ab33393 --- /dev/null +++ b/scripts/mangleErrors.js @@ -0,0 +1,151 @@ +const fs = require('fs') +const helperModuleImports = require('@babel/helper-module-imports') + +/** + * Converts an AST type into a javascript string so that it can be added to the error message lookup. + * + * Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some + * adjustments + */ +const evalToString = ast => { + switch (ast.type) { + case 'StringLiteral': + case 'Literal': // ESLint + return ast.value + case 'BinaryExpression': // `+` + if (ast.operator !== '+') { + throw new Error('Unsupported binary operator ' + ast.operator) + } + return evalToString(ast.left) + evalToString(ast.right) + case 'TemplateLiteral': + return ast.quasis.reduce( + (concatenatedValue, templateElement) => + concatenatedValue + templateElement.value.raw, + '' + ) + case 'Identifier': + return ast.name + default: + throw new Error('Unsupported type ' + ast.type) + } +} + +/** + * Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a + * smaller bundle size in production for consumers. + * + * If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. + * + * If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a + * an error number index in production or the actual error message in development. This allows consumers using webpak + * or another build tool to have these messages in development but have just the error index in production. + * + * E.g. + * Before: + * throw new Error("This is my error message."); + * throw new Error("This is a second error message."); + * + * After (with minify): + * throw new Error(0); + * throw new Error(1); + * + * After: (without minify): + * throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message."); + * throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message."); + */ +module.exports = babel => { + const t = babel.types + // When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the + // indexes do not change between builds. + let errorsFiles = '' + if (fs.existsSync('errors.json')) { + errorsFiles = fs.readFileSync('errors.json').toString() + } + let errors = Object.values(JSON.parse(errorsFiles || '{}')) + // This variable allows us to skip writing back to the file if the errors array hasn't changed + let changeInArray = false + + return { + pre: () => { + changeInArray = false + }, + visitor: { + ThrowStatement(path, file) { + const arguments = path.node.argument.arguments + const minify = file.opts.minify + + if (arguments && arguments[0]) { + // Skip running this logic when certain types come up: + // Identifier comes up when a variable is thrown (E.g. throw new error(message)) + // NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed + if ( + path.node.argument.arguments[0].type === 'Identifier' || + path.node.argument.arguments[0].type === 'NumericLiteral' || + path.node.argument.arguments[0].type === 'ConditionalExpression' || + path.node.argument.arguments[0].type === 'CallExpression' + ) { + return + } + + const errorMsgLiteral = evalToString(path.node.argument.arguments[0]) + + if (errorMsgLiteral.includes('Super expression')) { + // ignore Babel runtime error message + return + } + + // Attempt to get the existing index of the error. If it is not found, add it to the array as a new error. + let errorIndex = errors.indexOf(errorMsgLiteral) + if (errorIndex === -1) { + errors.push(errorMsgLiteral) + errorIndex = errors.length - 1 + changeInArray = true + } + + // Import the error message function + const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( + path, + 'src/utils/formatProdErrorMessage', + { nameHint: 'formatProdErrorMessage' } + ) + + // Creates a function call to output the message to the error code page on the website + const prodMessage = t.callExpression( + formatProdErrorMessageIdentifier, + [t.numericLiteral(errorIndex)] + ) + + if (minify) { + path.replaceWith( + t.throwStatement( + t.newExpression(t.identifier('Error'), [prodMessage]) + ) + ) + } else { + path.replaceWith( + t.throwStatement( + t.newExpression(t.identifier('Error'), [ + t.conditionalExpression( + t.binaryExpression( + '===', + t.identifier('process.env.NODE_ENV'), + t.stringLiteral('production') + ), + prodMessage, + path.node.argument.arguments[0] + ) + ]) + ) + ) + } + } + } + }, + post: () => { + // If there is a new error in the array, convert it to an indexed object and write it back to the file. + if (changeInArray) { + fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2)) + } + } + } +} diff --git a/src/createStore.js b/src/createStore.js index 45b09aca00..0b2db637e0 100644 --- a/src/createStore.js +++ b/src/createStore.js @@ -126,7 +126,7 @@ export default function createStore(reducer, preloadedState, enhancer) { 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + - 'See https://redux.js.org/api-reference/store#subscribelistener for more details.' + 'See https://redux.js.org/api/store#subscribelistener for more details.' ) } @@ -143,7 +143,7 @@ export default function createStore(reducer, preloadedState, enhancer) { if (isDispatching) { throw new Error( 'You may not unsubscribe from a store listener while the reducer is executing. ' + - 'See https://redux.js.org/api-reference/store#subscribelistener for more details.' + 'See https://redux.js.org/api/store#subscribelistener for more details.' ) } diff --git a/src/utils/formatProdErrorMessage.js b/src/utils/formatProdErrorMessage.js new file mode 100644 index 0000000000..3ae0234656 --- /dev/null +++ b/src/utils/formatProdErrorMessage.js @@ -0,0 +1,15 @@ +/** + * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js + * + * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes + * during build. + * @param {number} code + */ +function formatProdErrorMessage(code) { + return ( + `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or ` + + 'use the non-minified dev environment for full errors. ' + ) +} + +export default formatProdErrorMessage From b3e26c67a86637b39cf11a503dc4b56ac71c9da0 Mon Sep 17 00:00:00 2001 From: Mark Erikson Date: Fri, 2 Apr 2021 18:00:50 -0400 Subject: [PATCH 2/4] Update mangleErrors to use a relative path for imports --- scripts/mangleErrors.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/mangleErrors.js b/scripts/mangleErrors.js index 2c4ab33393..fcd7e7391d 100644 --- a/scripts/mangleErrors.js +++ b/scripts/mangleErrors.js @@ -103,9 +103,10 @@ module.exports = babel => { } // Import the error message function + // Note that all of our error messages are in `src`, so we can assume a relative path here const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( path, - 'src/utils/formatProdErrorMessage', + './utils/formatProdErrorMessage', { nameHint: 'formatProdErrorMessage' } ) From 46f5c94d42db86097e92617add8fda3ecb4f127e Mon Sep 17 00:00:00 2001 From: Mark Erikson Date: Fri, 2 Apr 2021 18:01:25 -0400 Subject: [PATCH 3/4] Port error message updates from master --- errors.json | 25 ++++++------ src/bindActionCreators.js | 8 ++-- src/combineReducers.js | 35 ++++++++--------- src/createStore.js | 41 +++++++++++++++----- src/utils/kindOf.js | 68 +++++++++++++++++++++++++++++++++ test/bindActionCreators.spec.js | 12 +++--- test/combineReducers.spec.js | 4 +- test/createStore.spec.js | 39 +++++++++++++++++-- 8 files changed, 176 insertions(+), 56 deletions(-) create mode 100644 src/utils/kindOf.js diff --git a/errors.json b/errors.json index 4c605cd2c1..2fac82d961 100644 --- a/errors.json +++ b/errors.json @@ -1,18 +1,19 @@ { - "0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.", - "1": "Expected the enhancer to be a function.", - "2": "Expected the reducer to be a function.", + "0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.", + "1": "Expected the enhancer to be a function. Instead, received: ''", + "2": "Expected the root reducer to be a function. Instead, received: ''", "3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.", - "4": "Expected the listener to be a function.", + "4": "Expected the listener to be a function. Instead, received: ''", "5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.", "6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.", - "7": "Actions must be plain objects. Use custom middleware for async actions.", - "8": "Actions may not have an undefined \"type\" property. Have you misspelled a constant?", + "7": "Actions must be plain objects. Instead, the actual type was: ''. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.", + "8": "Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.", "9": "Reducers may not dispatch actions.", - "10": "Expected the nextReducer to be a function.", - "11": "Expected the observer to be an object.", - "12": "bindActionCreators expected an object or a function, instead received . Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?", - "13": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.", - "14": "Reducer \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.", - "15": "Reducer \"\" returned undefined when probed with a random type. Don't try to handle or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null." + "10": "Expected the nextReducer to be a function. Instead, received: '", + "11": "Expected the observer to be an object. Instead, received: ''", + "12": "The slice reducer for key \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.", + "13": "The slice reducer for key \"\" returned undefined when probed with a random type. Don't try to handle '' or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.", + "14": "When called with an action of type , the slice reducer for key \"\" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.", + "15": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.", + "16": "bindActionCreators expected an object or a function, but instead received: ''. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?" } \ No newline at end of file diff --git a/src/bindActionCreators.js b/src/bindActionCreators.js index dd78819e56..8e610e8572 100644 --- a/src/bindActionCreators.js +++ b/src/bindActionCreators.js @@ -1,3 +1,5 @@ +import { kindOf } from './utils/kindOf' + function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(this, arguments)) @@ -32,9 +34,9 @@ export default function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error( - `bindActionCreators expected an object or a function, instead received ${ - actionCreators === null ? 'null' : typeof actionCreators - }. ` + + `bindActionCreators expected an object or a function, but instead received: '${kindOf( + actionCreators + )}'. ` + `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?` ) } diff --git a/src/combineReducers.js b/src/combineReducers.js index dcf06f2829..6ed79c245c 100644 --- a/src/combineReducers.js +++ b/src/combineReducers.js @@ -1,18 +1,7 @@ import ActionTypes from './utils/actionTypes' import warning from './utils/warning' import isPlainObject from './utils/isPlainObject' - -function getUndefinedStateErrorMessage(key, action) { - const actionType = action && action.type - const actionDescription = - (actionType && `action "${String(actionType)}"`) || 'an action' - - return ( - `Given ${actionDescription}, reducer "${key}" returned undefined. ` + - `To ignore an action, you must explicitly return the previous state. ` + - `If you want this reducer to hold no value, you can return null instead of undefined.` - ) -} +import { kindOf } from './utils/kindOf' function getUnexpectedStateShapeWarningMessage( inputState, @@ -35,9 +24,9 @@ function getUnexpectedStateShapeWarningMessage( if (!isPlainObject(inputState)) { return ( - `The ${argumentName} has unexpected type of "` + - {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + - `". Expected argument to be an object with the following ` + + `The ${argumentName} has unexpected type of "${kindOf( + inputState + )}". Expected argument to be an object with the following ` + `keys: "${reducerKeys.join('", "')}"` ) } @@ -69,7 +58,7 @@ function assertReducerShape(reducers) { if (typeof initialState === 'undefined') { throw new Error( - `Reducer "${key}" returned undefined during initialization. ` + + `The slice reducer for key "${key}" returned undefined during initialization. ` + `If the state passed to the reducer is undefined, you must ` + `explicitly return the initial state. The initial state may ` + `not be undefined. If you don't want to set a value for this reducer, ` + @@ -83,8 +72,8 @@ function assertReducerShape(reducers) { }) === 'undefined' ) { throw new Error( - `Reducer "${key}" returned undefined when probed with a random type. ` + - `Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` + + `The slice reducer for key "${key}" returned undefined when probed with a random type. ` + + `Don't try to handle '${ActionTypes.INIT}' or other actions in "redux/*" ` + `namespace. They are considered private. Instead, you must return the ` + `current state for any unknown actions, unless it is undefined, ` + `in which case you must return the initial state, regardless of the ` + @@ -167,8 +156,14 @@ export default function combineReducers(reducers) { const previousStateForKey = state[key] const nextStateForKey = reducer(previousStateForKey, action) if (typeof nextStateForKey === 'undefined') { - const errorMessage = getUndefinedStateErrorMessage(key, action) - throw new Error(errorMessage) + const actionType = action && action.type + throw new Error( + `When called with an action of type ${ + actionType ? `"${String(actionType)}"` : '(unknown type)' + }, the slice reducer for key "${key}" returned undefined. ` + + `To ignore an action, you must explicitly return the previous state. ` + + `If you want this reducer to hold no value, you can return null instead of undefined.` + ) } nextState[key] = nextStateForKey hasChanged = hasChanged || nextStateForKey !== previousStateForKey diff --git a/src/createStore.js b/src/createStore.js index 0b2db637e0..5326a52ff8 100644 --- a/src/createStore.js +++ b/src/createStore.js @@ -2,6 +2,7 @@ import $$observable from 'symbol-observable' import ActionTypes from './utils/actionTypes' import isPlainObject from './utils/isPlainObject' +import { kindOf } from './utils/kindOf' /** * Creates a Redux store that holds the state tree. @@ -36,7 +37,7 @@ export default function createStore(reducer, preloadedState, enhancer) { throw new Error( 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + - 'together to a single function.' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.' ) } @@ -47,14 +48,22 @@ export default function createStore(reducer, preloadedState, enhancer) { if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { - throw new Error('Expected the enhancer to be a function.') + throw new Error( + `Expected the enhancer to be a function. Instead, received: '${kindOf( + enhancer + )}'` + ) } return enhancer(createStore)(reducer, preloadedState) } if (typeof reducer !== 'function') { - throw new Error('Expected the reducer to be a function.') + throw new Error( + `Expected the root reducer to be a function. Instead, received: '${kindOf( + reducer + )}'` + ) } let currentReducer = reducer @@ -118,7 +127,11 @@ export default function createStore(reducer, preloadedState, enhancer) { */ function subscribe(listener) { if (typeof listener !== 'function') { - throw new Error('Expected the listener to be a function.') + throw new Error( + `Expected the listener to be a function. Instead, received: '${kindOf( + listener + )}'` + ) } if (isDispatching) { @@ -184,15 +197,15 @@ export default function createStore(reducer, preloadedState, enhancer) { function dispatch(action) { if (!isPlainObject(action)) { throw new Error( - 'Actions must be plain objects. ' + - 'Use custom middleware for async actions.' + `Actions must be plain objects. Instead, the actual type was: '${kindOf( + action + )}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.` ) } if (typeof action.type === 'undefined') { throw new Error( - 'Actions may not have an undefined "type" property. ' + - 'Have you misspelled a constant?' + 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.' ) } @@ -228,7 +241,11 @@ export default function createStore(reducer, preloadedState, enhancer) { */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { - throw new Error('Expected the nextReducer to be a function.') + throw new Error( + `Expected the nextReducer to be a function. Instead, received: '${kindOf( + nextReducer + )}` + ) } currentReducer = nextReducer @@ -259,7 +276,11 @@ export default function createStore(reducer, preloadedState, enhancer) { */ subscribe(observer) { if (typeof observer !== 'object' || observer === null) { - throw new TypeError('Expected the observer to be an object.') + throw new TypeError( + `Expected the observer to be an object. Instead, received: '${kindOf( + observer + )}'` + ) } function observeState() { diff --git a/src/utils/kindOf.js b/src/utils/kindOf.js new file mode 100644 index 0000000000..e8b352a1c5 --- /dev/null +++ b/src/utils/kindOf.js @@ -0,0 +1,68 @@ +export function kindOf(val) { + let typeOfVal = typeof val + + if (process.env.NODE_ENV !== 'production') { + // Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of + function miniKindOf(val) { + if (val === void 0) return 'undefined' + if (val === null) return 'null' + + const type = typeof val + switch (type) { + case 'boolean': + case 'string': + case 'number': + case 'symbol': + case 'function': { + return type + } + default: break; + } + + if (Array.isArray(val)) return 'array' + if (isDate(val)) return 'date' + if (isError(val)) return 'error' + + const constructorName = ctorName(val) + switch (constructorName) { + case 'Symbol': + case 'Promise': + case 'WeakMap': + case 'WeakSet': + case 'Map': + case 'Set': + return constructorName + default: break; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, '') + } + + function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null + } + + function isError(val) { + return ( + val instanceof Error || + (typeof val.message === 'string' && + val.constructor && + typeof val.constructor.stackTraceLimit === 'number') + ) + } + + function isDate(val) { + if (val instanceof Date) return true + return ( + typeof val.toDateString === 'function' && + typeof val.getDate === 'function' && + typeof val.setDate === 'function' + ) + } + + typeOfVal = miniKindOf(val) + } + + return typeOfVal +} diff --git a/test/bindActionCreators.spec.js b/test/bindActionCreators.spec.js index 54031dbbee..1cebddb13e 100644 --- a/test/bindActionCreators.spec.js +++ b/test/bindActionCreators.spec.js @@ -75,8 +75,8 @@ describe('bindActionCreators', () => { expect(() => { bindActionCreators(undefined, store.dispatch) }).toThrow( - 'bindActionCreators expected an object or a function, instead received undefined. ' + - 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' + `bindActionCreators expected an object or a function, but instead received: 'undefined'. ` + + `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?` ) }) @@ -84,8 +84,8 @@ describe('bindActionCreators', () => { expect(() => { bindActionCreators(null, store.dispatch) }).toThrow( - 'bindActionCreators expected an object or a function, instead received null. ' + - 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' + `bindActionCreators expected an object or a function, but instead received: 'null'. ` + + `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?` ) }) @@ -93,8 +93,8 @@ describe('bindActionCreators', () => { expect(() => { bindActionCreators('string', store.dispatch) }).toThrow( - 'bindActionCreators expected an object or a function, instead received string. ' + - 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?' + `bindActionCreators expected an object or a function, but instead received: 'string'. ` + + `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?` ) }) }) diff --git a/test/combineReducers.spec.js b/test/combineReducers.spec.js index cfd712da38..a72c1541dd 100644 --- a/test/combineReducers.spec.js +++ b/test/combineReducers.spec.js @@ -235,7 +235,7 @@ describe('Utils', () => { createStore(reducer, 1) expect(spy.mock.calls[2][0]).toMatch( - /createStore has unexpected type of "Number".*keys: "foo", "baz"/ + /createStore has unexpected type of "number".*keys: "foo", "baz"/ ) reducer({ corge: 2 }) @@ -250,7 +250,7 @@ describe('Utils', () => { reducer(1) expect(spy.mock.calls[5][0]).toMatch( - /reducer has unexpected type of "Number".*keys: "foo", "baz"/ + /reducer has unexpected type of "number".*keys: "foo", "baz"/ ) spy.mockClear() diff --git a/test/createStore.spec.js b/test/createStore.spec.js index 9bbac18428..dcbf65cf3e 100644 --- a/test/createStore.spec.js +++ b/test/createStore.spec.js @@ -503,6 +503,27 @@ describe('createStore', () => { ) }) + it('throws an error that correctly describes the type of item dispatched', () => { + const store = createStore(reducers.todos) + expect(() => store.dispatch(Promise.resolve(42))).toThrow( + /the actual type was: 'Promise'/ + ) + + expect(() => store.dispatch(() => {})).toThrow( + /the actual type was: 'function'/ + ) + + expect(() => store.dispatch(new Date())).toThrow( + /the actual type was: 'date'/ + ) + + expect(() => store.dispatch(null)).toThrow(/the actual type was: 'null'/) + + expect(() => store.dispatch(undefined)).toThrow( + /the actual type was: 'undefined'/ + ) + }) + it('throws if action type is undefined', () => { const store = createStore(reducers.todos) expect(() => store.dispatch({ type: undefined })).toThrow( @@ -630,15 +651,27 @@ describe('createStore', () => { expect(function () { obs.subscribe() - }).toThrowError(new TypeError('Expected the observer to be an object.')) + }).toThrowError( + new TypeError( + `Expected the observer to be an object. Instead, received: 'undefined'` + ) + ) expect(function () { obs.subscribe(null) - }).toThrowError(new TypeError('Expected the observer to be an object.')) + }).toThrowError( + new TypeError( + `Expected the observer to be an object. Instead, received: 'null'` + ) + ) expect(function () { obs.subscribe(() => {}) - }).toThrowError(new TypeError('Expected the observer to be an object.')) + }).toThrowError( + new TypeError( + `Expected the observer to be an object. Instead, received: 'function'` + ) + ) expect(function () { obs.subscribe({}) From 3ce88ddbe72be0cbf101421b6837bb29518a880a Mon Sep 17 00:00:00 2001 From: Mark Erikson Date: Fri, 2 Apr 2021 18:07:59 -0400 Subject: [PATCH 4/4] Formatting --- src/utils/kindOf.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/utils/kindOf.js b/src/utils/kindOf.js index e8b352a1c5..c5395a1df6 100644 --- a/src/utils/kindOf.js +++ b/src/utils/kindOf.js @@ -16,7 +16,8 @@ export function kindOf(val) { case 'function': { return type } - default: break; + default: + break } if (Array.isArray(val)) return 'array' @@ -32,7 +33,8 @@ export function kindOf(val) { case 'Map': case 'Set': return constructorName - default: break; + default: + break } // other