gpt4 book ai didi

typescript - thunkAPI.getState 不是函数 : Error with reduxtoolkit and jest

转载 作者:行者123 更新时间:2023-12-03 08:16:00 26 4
gpt4 key购买 nike

我正在使用 createAsyncThunk 并使用 jest/ReduxToolkit/TypeScript 为其编写测试。

这是我的切片。

export const getUsers = createAsyncThunk<object[], undefined, { state: RootState }>(
'user/getUsers',
(_: undefined, thunkAPI) => {
const { users } = thunkAPI.getState().user;
if (!users) {
// fetch users
}
return users;
},
);

const userSlice = createSlice({
name: 'user',
initialState: {
users: [],
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(getUsers.fulfilled, (state, action) => {
state.users = action.payload;
});
},
});

export default userSlice;

这是我的测试。

let store: EnhancedStore;

beforeEach(() => {
store = configureStore({
reducer: {
user: userSlice.reducer,
},
});
});

describe('userSlice', () => {
test('getUsers success', async () => {
const state = await getUsers();
const result = await state(store.dispatch, store.getState(), undefined);
console.log(result)
expect(result.type).toBe('user/getUsers/fulfilled');
expect(result.meta.requestStatus).toBe('fulfilled');
});
});

当我运行测试时,我收到错误和日志输出:

{type: 'user/getUsers/rejected',payload: undefined,meta: {arg: undefined,requestId: '***************',rejectedWithValue: false,requestStatus: 'rejected',aborted: false,condition: false},error: {name: 'TypeError',message: 'thunkAPI.getState is not a function',stack: 'TypeError: thunkAPI.getState is not a function\n' + // omitted}}

所以我理解错误消息 TypeError: thunkAPI.getState is not a function 指出切片中的 thunkAPI.getState() 导致错误,但它并没有使用网络浏览器运行时会导致任何错误。

有人有想法吗?谢谢。

版本

  • react-redux v7.2.5
  • reduxjs/工具包 v1.6.1
  • Jest v27.0.6
  • ts-jest v27.0.5

最佳答案

推断出的state变量的TS类型是:

const state: (dispatch: ThunkDispatch<any, unknown, AnyAction>, getState: () => any, extra: unknown) => Promise<PayloadAction<object[], string, {
arg: undefined;
requestId: string;
requestStatus: "fulfilled";
}, never> | PayloadAction<...>> & {
...;
}

您应该将 store.getState 而不是 store.getState() 传递给 state。所以应该是:

const result = await state(store.dispatch, store.getState, undefined);

不是:

const result = await state(store.dispatch, store.getState(), undefined);

关于typescript - thunkAPI.getState 不是函数 : Error with reduxtoolkit and jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69369939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com