- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 redux 工具包库的新手,尤其是在测试方面。我浏览了文档并阅读了一堆关于这个主题的帖子和文章,但仍然很挣扎。我构建了一个简单的待办事项应用程序,并包含了几个 API 请求来涵盖异步情况。不过,测试这些结果有点挑战性。我希望就我的代码以及可以改进的地方获得一些建议和反馈。我还想对测试 createAsyncThunk 切片是否有意义提出一些意见。注意:我对测试 API 调用本身不感兴趣,并使用模拟数据重新创建成功的请求。
build 性的批评非常有帮助,将不胜感激
请看一下我的切片文件并进行测试
postSlice.ts
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { RootState } from "../../store";
import axios from "axios";
export type Post = {
userId: number;
id: number;
title: string;
body: string;
};
export type PostsState = {
posts: Post[];
loading: boolean;
error: null | string;
};
export const initalPostState: PostsState = {
posts: [],
loading: false,
error: null,
};
export const fetchAllPosts = createAsyncThunk(
"posts/allPosts",
async (data, { rejectWithValue }) => {
try {
const response = await axios.get(
`https://jsonplaceholder.typicode.com/posts`
);
return (await response.data) as Post[];
} catch (err) {
if (!err.response) {
throw err;
}
return rejectWithValue(err.response.data);
}
}
);
export const fetchSuccessful = fetchAllPosts.fulfilled;
export const fetchPending = fetchAllPosts.pending;
export const fetchFailed = fetchAllPosts.rejected;
const postsSlice = createSlice({
name: "Posts",
initialState: initalPostState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchSuccessful, (state, { payload }) => {
state.posts = payload;
state.loading = false;
});
builder.addCase(fetchPending, (state, action) => {
state.loading = true;
});
builder.addCase(fetchFailed, (state, action) => {
state.error = action.error.message
? action.error.message
: "Failed to load data";
state.loading = false;
});
},
});
export const selectPosts = (state: RootState) => state.fetchedPosts;
export const fetchedPostsReducer = postsSlice.reducer;
import {
initalPostState,
fetchPending,
fetchFailed,
selectPosts,
fetchSuccessful,
fetchedPostsReducer,
} from "./postsSlice";
import { Post, PostsState } from "./postsSlice";
import store, { RootState } from "../../store";
const appState = store.getState();
describe("postsSlice", () => {
describe("Posts State, Posts Action and Selector", () => {
it("should set loading state on true when API call is pending", async (done) => {
// Arrange
// Act
const nextState: PostsState = await fetchedPostsReducer(
initalPostState,
fetchPending
);
// Assert
const rootState: RootState = { ...appState, fetchedPosts: nextState };
expect(selectPosts(rootState).loading).toBeTruthy();
expect(selectPosts(rootState).error).toBeNull();
done();
});
it("should set error state when API call is rejected", async (done) => {
// Arrange
const response = {
message: "Network request failed",
name: "error",
};
// Act
const nextState: PostsState = await fetchedPostsReducer(
initalPostState,
fetchFailed(response, "")
);
// Assert
const rootState: RootState = { ...appState, fetchedPosts: nextState };
expect(selectPosts(rootState).loading).toBeFalsy();
expect(selectPosts(rootState).error).not.toBeNull();
expect(selectPosts(rootState).error).toEqual("Network request failed");
done();
});
it("should update state when API call is successful", async (done) => {
// Arrange
const response: Post[] = [
{
userId: 1,
id: 1,
title:
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body:
"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
},
{
userId: 1,
id: 2,
title: "qui est esse",
body:
"est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
},
];
// Act
const nextState: PostsState = await fetchedPostsReducer(
initalPostState,
fetchSuccessful(response, "")
);
// Assert
const rootState: RootState = { ...appState, fetchedPosts: nextState };
expect(selectPosts(rootState).loading).toBeFalsy();
expect(selectPosts(rootState).error).toBeNull();
expect(selectPosts(rootState).posts).toEqual(
expect.arrayContaining(response)
);
done();
});
});
});
最佳答案
我已经在 GitHub 上回答了 redux 工具包的问题,但我也会在这里发帖,因为这是我在尝试自己的解决方案之前访问的众多链接之一。
解释
由于createAsyncThunk
返回一个函数供以后执行,您可以利用它来发挥自己的优势。无需麻烦地测试整个商店与您的 thunk 的交互,您可以在远离商店的情况下单独测试 thunk 本身。
运行您的jest.mock
调用模拟您可能用来访问服务器或本地状态的任何 API/ Hook ,更改这些解析/返回的内容,然后执行您保存的方法。这样做可以让您访问 createAsyncThunk
中的 promise /方法。使用您通常会调用的参数进行调用。
具体问题
您不想测试商店,而是要测试 thunk 是否正在调度商店所依赖的操作来设置诸如加载、您要保存的错误消息等。这样您就可以为您的 reducer 创建测试,其中您可以在每次测试时重新创建一个全新的商店,并确保通过这些 reducer 进行的所有转换都是正确的。
通克
// features/account/thunks.ts
import api from './api'; // http calls to the API
import { actions } from './reducer'; // "actions" from a createSlice result
import { useRefreshToken } from './hooks'; // a `useSelector(a => a.account).auth?.refreshToken` result
// declare and code as normal
export const register = createAsyncThunk(
'accounts/register',
async (arg: IRegisterProps, { dispatch }) => {
try {
const data = await api.register(arg);
dispatch(actions.authSuccess(data));
} catch (err) {
console.error('Unable to register', err);
}
}
);
// Using a hook to access state
export const refreshSession = createAsyncThunk(
'accounts/refreshSession',
async (_, { dispatch }) => {
// or add `, getState` beside dispatch and do token = getState().accounts.auth.refreshToken;
// If you use getState, your test will be more verbose though
const token: string = useRefreshToken();
try {
const data = await api.refreshToken(token);
dispatch(actions.tokenRefreshed(data));
} catch (err) {
console.error('Unable to refresh token', err);
}
}
);
考试
// features/account/thunks.test.ts
import apiModule from './api';
import hookModule from './hooks';
import thunks from './thunks';
import { actions } from './reducer';
import { IRegisterProps } from './types';
import { AsyncThunkAction, Dispatch } from '@reduxjs/toolkit';
import { IAuthSuccess } from 'types/auth';
jest.mock('./api');
jest.mock('./hooks')
describe('Account Thunks', () => {
let api: jest.Mocked<typeof apiModule>;
let hooks: jest.Mocked<typeof hookModule>
beforeAll(() => {
api = apiModule as any;
hooks = hookModule as any;
});
// Clean up after yourself.
// Do you want bugs? Because that's how you get bugs.
afterAll(() => {
jest.unmock('./api');
jest.unmock('./hooks');
});
describe('register', () => {
// We're going to be using the same argument, so we're defining it here
// The 3 types are <What's Returned, Argument, Thunk Config>
let action: AsyncThunkAction<void, IRegisterProps, {}>;
let dispatch: Dispatch; // Create the "spy" properties
let getState: () => unknown;
let arg: IRegisterProps;
let result: IAuthSuccess;
beforeEach(() => {
// initialize new spies
dispatch = jest.fn();
getState = jest.fn();
api.register.mockClear();
api.register.mockResolvedValue(result);
arg = { email: 'me@myemail.com', password: 'yeetmageet123' };
result = { accessToken: 'access token', refreshToken: 'refresh token' };
action = thunks.registerNewAccount(arg);
});
// Test that our thunk is calling the API using the arguments we expect
it('calls the api correctly', async () => {
await action(dispatch, getState, undefined);
expect(api.register).toHaveBeenCalledWith(arg);
});
// Confirm that a success dispatches an action that we anticipate
it('triggers auth success', async () => {
const call = actions.authSuccess(result);
await action(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledWith(call);
});
});
describe('refreshSession', () => {
// We're going to be using the same argument, so we're defining it here
// The 3 types are <What's Returned, Argument, Thunk Config>
let action: AsyncThunkAction<void, unknown, {}>;
let dispatch: Dispatch; // Create the "spy" properties
let getState: () => unknown;
let result: IAuthSuccess;
let existingToken: string;
beforeEach(() => {
// initialize new spies
dispatch = jest.fn();
getState = jest.fn();
existingToken = 'access-token-1';
hooks.useRefreshToken.mockReturnValue(existingToken);
api.refreshToken.mockClear();
api.refreshToken.mockResolvedValue(result);
result = { accessToken: 'access token', refreshToken: 'refresh token 2' };
action = thunks.refreshSession();
});
it('does not call the api if the access token is falsy', async () => {
hooks.useRefreshToken.mockReturnValue(undefined);
await action(dispatch, getState, undefined);
expect(api.refreshToken).not.toHaveBeenCalled();
});
it('uses a hook to access the token', async () => {
await action(dispatch, getState, undefined);
expect(hooks.useRefreshToken).toHaveBeenCalled();
});
// Test that our thunk is calling the API using the arguments we expect
it('calls the api correctly', async () => {
await action(dispatch, getState, undefined);
expect(api.refreshToken).toHaveBeenCalledWith(existingToken);
});
// Confirm a successful action that we anticipate has been dispatched too
it('triggers auth success', async () => {
const call = actions.tokenRefreshed(result);
await action(dispatch, getState, undefined);
expect(dispatch).toHaveBeenCalledWith(call);
});
});
});
关于测试 createAsyncThunk Redux Toolkit Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62253049/
有如下组件代码: import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import {
我有一个 thunk Action 是由 createAsyncThunk 创建的.我想在调用 api 更新状态之前调度一个 Action 。 我不想使用 Action getProducts.pen
所以我是 redux-toolkit 的新手,我想做一些非常简单的事情。我想通过这个辅助函数发送一些关于 POST 请求的数据。所以我尝试了这个 export const submitPaymentT
我正在使用 createAsyncThunk向某些 API 发出异步请求。在任何给定时刻,只有一个请求处于事件状态。 我知道可以使用提供的 AbortSignal 中止请求如果我从上一次调用中返回了
我是 redux 工具包库的新手,尤其是在测试方面。我浏览了文档并阅读了一堆关于这个主题的帖子和文章,但仍然很挣扎。我构建了一个简单的待办事项应用程序,并包含了几个 API 请求来涵盖异步情况。不过,
使用 Redux-Toolkit,我尝试在 createAsyncThunk 中使用 ThunkAPI 和分派(dispatch),但由于类型错误而被拒绝。不确定如何解决这个问题。 我的商店: exp
当 fetchUserById() 创建时,它的输出响应被定义。 const fetchUserById = createAsyncThunk( 'users/fetchByIdStatus',
我熟悉 react hooks,我发现使用 useEffect 真的很容易,thunk 很难处理,我可以只使用 useEffect 和 axios 并将结果发送到商店而不使用 createAsyncT
我正在从 Redux 迁移到 Redux Toolkit。我这里的简化代码用于使用 lodash/debounce 进行去抖动更新。 import debounce from "lodash/debo
我是 Redux/Redux-Toolkit 的新手,我一直在尝试使用 RTK 为异步方法提供的 createAsyncThunk 方法获取一些数据,但我遇到了一些问题,我的有效负载刚刚“完成”返回空
我有一个 react/typescript 项目。我正在使用 redux 来管理状态。 //store.ts import { configureStore, combineReducers } fr
有人可以像我 9 岁那样向我解释什么以及如何使用 createAsyncThunk 吗? Action 字符串有什么用?它是出于逻辑/路径原因临时创建并很快销毁吗?我可以用操作字符串做什么/人们通常用
我无法设置 getState() 的返回类型至RootState .我正在使用 typescript 和 VSCode。我必须将类型设置为 any ,这会停止该对象上的 IntelliSense。下面
环境 Redux 工具包 react typescript Grpahql 背景 我正在使用 redux 和 redux-toolkit 进行本地状态管理。我阅读了 redux-toolkit 文档。
环境 Redux 工具包 react typescript Grpahql 背景 我正在使用 redux 和 redux-toolkit 进行本地状态管理。我阅读了 redux-toolkit 文档。
我想为我工作的项目中的用户创建一个 Redux 切片。我有 this code sandbox而且我不知道为什么 MyButton.tsx 文件中的 fetchAll 调用会出现以下错误: fetch
我在看 createAsyncThunk文档,感觉有点与流程混淆。这是来自文档: import { createAsyncThunk, createSlice } from '@reduxjs/too
我对 redux 工具包还很陌生,所以我仍然有一些问题! 根据下面的代码,我正在尝试访问我的 loginDetails.username 中的状态( loginDetails.password 和 c
我目前正在设置我的 RTK (Redux Toolkit) 并进行了一些小测试。这是我的代码: 存储/index.js import { configureStore } from '@reduxjs
我刚开始使用 Redux Toolkit(RTK),我很难找到从 RTK 使用 createAsyncThunk 的正确方法。 所以我想做的是 调度由 createAsyncThunk 创建的异步操作
我是一名优秀的程序员,十分优秀!