使用 async redux-thunk 操作对商店更改打字稿进行功能测试

Functional test with typescript of store change with async redux-thunk action

我在 React 中使用打字稿进行了功能测试,以便在获取 post.

的异步操作后测试正确的存储行为

我已经创建了带有文件的单独实用程序和测试商店:

export const testStore = (initialState: State={posts: []}) => {
    const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore)
    return createStoreWithMiddleware(rootReducer, initialState);
}

然后我编写了如下实现的测试:

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);
    });
});

一切似乎都正常,但以下行除外:await store.dispatch(fetchPosts());

存在打字稿错误: TS2345:'ThunkAction' 类型的参数不可分配给 'Action' 类型的参数。类型 'ThunkAction' 缺少类型 'ActionGetUser' 的以下属性:类型、有效载荷

Link 回购项目https://github.com/pirx1988/react-store-testing/tree/develop

带有测试的文件路径:/src/integrationTests/index.test.ts

我该如何处理?我已经用中间件 redux-thunk 创建了一个商店,但是 dispatch 无法理解这里的异步 thunk fetchPosts 操作并期望使用普通对象的操作。

您可以使用以下方法修复它:

await (store.dispatch as ThunkDispatch<State, unknown, Actions>)(fetchPosts());