Home > front end >  test conditional inside reducer switch in react
test conditional inside reducer switch in react

Time:06-02

Here i have a reducer which i'm testing at the moment, in my test coverage it shows Uncovered Line : this part 'return action.payload;' which is inside 'changeNode' function, any advice on how to test if else ? (i have many cases inside my switch and few of them have if else, if i solve this one i could solves those others easily)

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),
        },
      };
      }
      
      
      
      

test:

 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,
            },
          },
        });
      });

CodePudding user response:

Well, your test does not actually test the "edit" functionality of the reducer, as you are testing against the initial state, which has no nodes.

You need to provide an initial state, currently the undefined you pass to reducers.graphArticle, with a couple of nodes, and then pass an action as the other parameter that will edit one of them, so that the test will go through the if and the else.

Something like

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);
});
  • Related