Skip to content

Instantly share code, notes, and snippets.

@jasonleehodges
Last active December 11, 2021 18:55
Show Gist options
  • Save jasonleehodges/78d5bdbad332ef51976de2cadabb06fc to your computer and use it in GitHub Desktop.
Save jasonleehodges/78d5bdbad332ef51976de2cadabb06fc to your computer and use it in GitHub Desktop.
Testable Redux Reducer
import {
PayloadAction,
createReducer,
} from "@reduxjs/toolkit";
import { increment, decrement, incrementByAmount, incrementAsync } from "./actions";
export interface CounterState {
value: number;
status: "idle" | "loading" | "failed";
}
const initialState: CounterState = {
value: 0,
status: "idle",
};
export const testableCounterReducer = createReducer(initialState, (builder) =>
builder
.addCase(increment, (state) => ({ ...state, value: state.value + 1 }))
.addCase(decrement, (state) => ({ ...state, value: state.value - 1 }))
.addCase(incrementByAmount, (state, action: PayloadAction<number>) => ({
...state,
value: state.value + action.payload,
}))
.addCase(incrementAsync.pending, (state) => ({
...state,
status: "loading",
}))
.addCase(incrementAsync.fulfilled, (state, action) => ({
...state,
status: "idle",
value: state.value + action.payload,
}))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment