如何为 createSlice() 的 extraReducers 编写测试(Jest + Enzyme)?

Posted

技术标签:

【中文标题】如何为 createSlice() 的 extraReducers 编写测试(Jest + Enzyme)?【英文标题】:How to write tests ( Jest + Enzyme ) for extraReducers of createSlice ()? 【发布时间】:2020-10-12 13:55:46 【问题描述】:

我已经开始使用@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;
    ,
  ,
);

//测试 .. 为 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 的逻辑!

【问题讨论】:

【参考方案1】:

您可以使用与您展示的相同的方式对其进行测试。

这里有一个简单的方法,可以根据createAsyncThunk 输出的操作类型来测试reducer 的逻辑。

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

【讨论】:

以上是关于如何为 createSlice() 的 extraReducers 编写测试(Jest + Enzyme)?的主要内容,如果未能解决你的问题,请参考以下文章

isinstance 如何为 List 工作?

如何为 tensorflow 服务准备预热请求文件?

如何为 OSX 菜单额外启用复制和粘贴

如何为sensio框架控制器监听器启用注解阅读器服务?

Redux - createSlice 内的标准化嵌套数据组织

如何在没有 createSlice 的情况下使用 createThunkAsync