繁体   English   中英

使用异步 redux-thunk 操作进行存储更改打字稿的功能测试

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

我在 React 中使用 typescript 编写了功能测试,以便在获取帖子的异步操作后测试正确的存储行为。

我创建了带有测试存储文件的单独实用程序:

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”类型中的以下属性:类型、负载

在此处输入图片说明

链接到项目的回购https : //github.com/pirx1988/react-store-testing/tree/develop

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM