reactjs - 如何为createSlice()的extraReducers编写测试(Jest + enzyme )?

标签 reactjs react-redux enzyme redux-thunk redux-toolkit

我已经开始使用@ reduxjs/toolkit创建我的应用程序,有点卡住了。我找不到任何资源可以指导我如何对extraReducers中的逻辑进行单元测试。任何帮助将是可观的。
例子:
例子:

const fetchList = createAsyncThunk('example/fetchList', async ({skip, reset, ...rest}) => {
  const request = {
    skip: reset ? initialState.skip : skip,
    ...rest,
  };
  return await getList(request);
});
const exampleSlice = createSlice({
  name: 'example',
  initialState: {id: '', list: []},
  reducers: {
    resetParams() {
      return {id: '', list: []}
    },
    setId(state, {payload}) {
      state.id = payload.id
    }
  },
  extraReducers: {
    [fetchList.pending]: (state) => {
      state.fetching = true;
    },
    [fetchList.fulfilled]: (state, {payload = []}) => {
      return {
        fetching: false,
        id: state.id + 1,
        list: payload
      }
    },
    [fetchList.rejected]: (state, {error}) => {
      state.fetching = false;
    },
  },
});
//测试.. for setId()
const initialState = {
  id: 1,
  list : []
}
const result = exampleSlice.reducer(initialState, exampleSlice.actions.setId({id: 10}))
expect(result.id).toEqual(10)
如何在extraReducers中测试fetchList.fulfilled和fetchList.rejected的逻辑!

最佳答案

您可以按照显示的方式对其进行测试。
这是一种简单的方法,可以根据createAsyncThunk输出的 Action 类型来测试化简器的逻辑。

import reducer, {
  fetchList
} from './exampleSlice';

describe('exampleSlice', () => {
  describe('reducers', () => {
    const initialState = { id: '', list: [], fetching: false }
    
    it('sets fetching true when fetchList is pending', () => {
      const action = { type: fetchList.pending.type };
      const state = reducer(initialState, action);
      expect(state).toEqual({ id: '', list: [], fetching: true });
    });

    it('sets the id and list when fetchList is fulfilled', () => {
      const action = { type: fetchList.fulfilled.type, payload: { id: 1, list: [2, 3]} };
      const state = reducer(initialState, action);
      expect(state).toEqual({ id: 1, list: [2, 3], fetching: false });
    });

    it('sets fetching false when fetchList is rejected', () => {
        const action = { type: fetchList.rejected.type, payload: { error: 'some error' } };
        const state = reducer(initialState, action);
        expect(state).toEqual({ id: '', list: [], fetching: false });
      });
  });

});
我还在演示CSB上提出了一个相同概念的简单示例:https://codesandbox.io/s/rtk-14-addmatcher-counter-test-l11mt?file=/src/features/counter/counterSlice.test.ts

关于reactjs - 如何为createSlice()的extraReducers编写测试(Jest + enzyme )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62518929/

相关文章:

javascript - React.js 中父子组件之间的通信

javascript - 每次点击都会 react 进度条

javascript - nextProps 键虽然有内容但神秘地无法访问

reactjs - 三元运算符用 Jest 测试用例

reactjs - 您的测试套件必须至少包含一项测试

reactjs - 输入 React Router 路由器组件?使困惑

Reactjs 如何模糊滚动上的背景图像?

reactjs - 使用 Redux 两个 React 表单组件之间的通信

javascript - 如何替换对象中键的值

reactjs - 使用 enzyme 测试 react 确认窗口