I have crated functional tests in React with typescript in order to test correct store behavior after async action of getting post.
I had created separate utility with file with testing store:
export const testStore = (initialState: State={posts: []}) => {
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore)
return createStoreWithMiddleware(rootReducer, initialState);
}
Then I wrote te tests inmplementation like below:
import {fetchPosts} from '../actions'
import axios, {AxiosResponse} from "axios";
import configureStore from 'redux-mock-store'
jest.mock('axios')
const mockedAxios = axios as jest.Mocked<typeof axios>;
import expectedPosts from "../__mocks__/expectedPosts";
import State from "../state";
import reduxThunk, { ThunkDispatch } from "redux-thunk";
import Action from "../actions/types";
import {testStore} from "../Utils";
type DispatchExts = ThunkDispatch<State, void, Action>
const middlewares = [reduxThunk];
const mockStore = configureStore<State, DispatchExts>(middlewares);
describe('fetchPosts action', () => {
it('Store is updated correctly', async () => {
const mockedResponse: AxiosResponse = {
data: expectedPosts,
status: 200,
statusText: 'OK',
headers: {},
config: {}
}
mockedAxios.get.mockResolvedValueOnce(mockedResponse);
const store = testStore({posts: []});
await store.dispatch(fetchPosts());
const newState = store.getState();
expect(newState.posts).toEqual(mockedResponse.data);
expect(newState.posts).not.toBe(mockedResponse.data);
});
});
Everything seems to be ok with exception with line: await store.dispatch(fetchPosts());
There is an typescript error: TS2345: Argument of type 'ThunkAction' is not assignable to parameter of type 'Action'. Type 'ThunkAction' is missing the following properties from type 'ActionGetUser': type, payload
Link to repo with project: https://github.com/pirx1988/react-store-testing/tree/develop
Path to file with test: /src/integrationTests/index.test.ts
How can I deal with it? I've created a store with middleware redux-thunk but dispatch can't understand async thunk fetchPosts action here and expect Action with plain object.
fechPosts()
apparently returnThunkAction
type andstore.dispatch()
expecting an Action type – GregMit