Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/toolkit/src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ export function createSlice<
if (!name) {
throw new Error('`name` is a required option for createSlice')
}

if (
typeof process !== 'undefined' &&
process.env.NODE_ENV === 'development'
) {
if(options.initialState === undefined) {
console.error('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`')
}
}

const initialState =
typeof options.initialState == 'function'
? options.initialState
Expand Down
23 changes: 23 additions & 0 deletions packages/toolkit/src/tests/createSlice.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
import type { PayloadAction } from '@reduxjs/toolkit'
import { createSlice, createAction } from '@reduxjs/toolkit'
import {
mockConsole,
createConsole,
getLog,
} from 'console-testing-library/pure'

describe('createSlice', () => {
let restore: () => void

beforeEach(() => {
restore = mockConsole(createConsole())
})

describe('when slice is undefined', () => {
it('should throw an error', () => {
expect(() =>
Expand Down Expand Up @@ -34,6 +45,18 @@ describe('createSlice', () => {
})
})

describe('when initial state is undefined', () => {
it('should throw an error', () => {
createSlice({
name: 'test',
reducers: {},
initialState: undefined,
})

expect(getLog().log).toBe('You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`')
})
})

describe('when passing slice', () => {
const { actions, reducer, caseReducers } = createSlice({
reducers: {
Expand Down