在反应中测试减速器开关内部的条件

test conditional inside reducer switch in react

这里我有一个正在测试的减速器,在我的测试范围内它显示了未覆盖的行:这部分 'return action.payload;' 在 'changeNode' 函数中,关于如何做的任何建议测试是否还有? (我的 switch 里面有很多案例,其中很少有 if else,如果我解决了这个问题,我可以轻松解决其他问题)

export function graphArticle(
  state = initialGraph,
  action: graphArticle
) {
  switch (action.type) {
   case ActionType.EDIT_NODE:
      const changeN = (n: any) => {
        if (n.id == action.payload.id) {
          return action.payload;
        } else {
          return n;
        }
      };
      return {
        ...state,
        graph: {
          ...state.graph,
          cameras: updateGraphC(state.graph, action.payload),
          model: {
            ...state.graph.model,
            nodes: state.graph.model?.nodes.map(changeN),
          },
          currentNode: changeN(state.currentNode),
        },
      };
      }
      
      
      
      

测试:

 it("EDIT_NODE ", () => {
        expect(
          reducers.graphArticle(undefined, {
            type: ActionType.EDIT_NODE,
            payload: {
              analyser_id: "yureg",
              id: 6,
            },
          })
        ).toEqual({
          floorplan: "",
          graph: {
            cameras: [],
            currentNode: "",
            model: {
              nodes: undefined,
            },
          },
        });
      });

嗯,您的测试实际上并没有测试 reducer 的“编辑”功能,因为您是针对没有节点的初始状态进行测试。

您需要提供一个初始状态,目前您传递给 reducers.graphArticleundefined,有几个节点,然后传递一个动作作为将编辑其中之一的另一个参数,以便测试将通过 ifelse.

类似

it("EDIT_NODE ", () => {
  const stateToEdit: InitialGraph = {
    floorplan: "",
    currentNode: "",
    graph: {
      cameras: [],
      model: {
        nodes: [{
          id: 1,
          analyser_id: "first"
        }, {
          id: 6,
          analyser_id: 'original'
        }, ],
      },
    },
  };
  const resultingStateAfterEdit: InitialGraph = {
    floorplan: "",
    currentNode: "",
    graph: {
      cameras: [],
      currentNode: "",
      model: {
        nodes: [{
          id: 1,
          analyser_id: "first"
        }, {
          id: 6,
          analyser_id: 'yureg'
        }, ],
      },
    },
  };

  expect(
    reducers.graphArticle(stateToEdit, {
      type: ActionType.EDIT_NODE,
      payload: {
        analyser_id: "yureg",
        id: 6,
      },
    })
  ).toEqual(resultingStateAfterEdit);
});