Steps:
To begin, utilize
jest.spyOn(MyService.prototype, 'postData')
for mocking the postData
method within the MyService
class along with its resolved/rejected value.
Next, establish a mock redux store to dispatch the async thunk and obtain the state using the store.getState()
API for asserting any changes.
For example:
index.ts
:
import { ActionReducerMapBuilder, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { MyService } from './my-service';
interface MyState {
data: any[];
}
const initialState: MyState = {
data: [],
};
export const postData = createAsyncThunk(
'data/postData',
async (
param: {
data: any[];
},
{ rejectWithValue },
) => {
try {
const myService: MyService = new MyService();
return await myService.postData(param.data);
} catch (error) {
console.error(error.message);
return rejectWithValue(error.message);
}
},
);
const combineExtraReducers = (builder: ActionReducerMapBuilder<MyState>) => {
builder.addCase(postData.fulfilled, (state, { payload }) => {
state.data = payload;
});
};
export const dataSlice = createSlice({
name: 'data',
initialState: initialState,
reducers: {},
extraReducers: (builder) => {
combineExtraReducers(builder);
},
});
my-service.ts
:
export class MyService {
async postData(params) {
return ['real data'];
}
}
index.test.ts
:
import { configureStore } from '@reduxjs/toolkit';
import { dataSlice, postData } from './';
import { MyService } from './my-service';
describe('UniqueID', () => {
afterEach(() => {
jest.restoreAllMocks();
});
test('verifying successful posting of data', async () => {
jest.spyOn(MyService.prototype, 'postData').mockResolvedValueOnce(['mock data']);
const store = configureStore({ reducer: dataSlice.reducer });
await store.dispatch(postData({ data: ['mock arg'] }));
expect(store.getState()).toEqual({ data: ['mock data'] });
});
});
Test outcome:
PASS redux-toolkit-example packages/redux-toolkit-example/stackoverflow/UniqueID/index.test.ts
UniqueID
✓ verifying successful posting of data (6 ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 85.71 | 100 | 83.33 | 83.33 |
index.ts | 87.5 | 100 | 100 | 85.71 | 24-25
my-service.ts | 80 | 100 | 50 | 75 | 3
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.609 s