【问题标题】:GET_SUCCESS in reducer test returns undefinedreducer 测试中的 GET_SUCCESS 返回 undefined
【发布时间】:2020-04-14 12:53:13
【问题描述】:
 it(`should handle ${GET_POSTAL_SUCCESS}`, () => {
      const payload = {
        postalCode: {
          postalInfo: {
            postalCode: '5282',
          },
        },
      };

      expect(reducer(state, { type: GET_POSTAL_SUCCESS, payload })).toEqual({
        ...state,
        postalInfo: payload.postalCode,
        loading: false,
      })
    });

第一个被接收,第二个被期望在代码块中。由于某种原因,它不会在这里很好地格式化。

错误:expect(received).toEqual(expected) // 深度相等

- 预期

+ 收到

 *Object {
    "loading": false,
-   "postalInfo": Object {
-     "postalInfo": Object {
-       "postalCode": "5282",
-     },
-   },*


**+   "postalInfo": undefined,**
  }

为什么 postalInfo 在收到此代码块时未定义?我就是不明白

 expect(reducer(state, { type: GET_POSTAL_SUCCESS, payload }))

这是我原来的减速器:

function reducer(state = defaultState, action) {
  switch (action.type) {
    case constants.GET_POSTAL:
      return {
        ...defaultState,
        code: action.code,
        loading: true,
      };
    case constants.GET_POSTAL_SUCCESS:
      return {
        ...state,
        postalInfo: action.payload.result,
        loading: false,
      };

到目前为止,这是我的全部测试:

 let state = reducer(undefined, {});

  it('should have initial state', () => {
    expect(state).toBeDefined();
  });


  describe('get postals', () => {

    it(`it should handle ${GET_POSTAL}`, () => {
      const code = '5282';
      expect(reducer(state, { type: GET_POSTAL, code })).toEqual({
        ...state,
        code,
        loading: true,
      });
    });

    it(`should handle ${GET_POSTAL_SUCCESS}`, () => {
      const payload = {
        postalCode: {
          postalInfo: {
            postalCode: '5282',
          },
        },
      };

      expect(reducer(state, { type: GET_POSTAL_SUCCESS, payload })).toEqual({
        ...state,
        postalInfo: payload.postalCode,
        loading: false,
      })
    });

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    在成功案例的减速器中,您将状态设置为action.payload.result

    case constants.GET_POSTAL_SUCCESS:
      return {
        ...state,
        postalInfo: action.payload.result,
        loading: false,
    };
    

    但在您的测试用例中,这就是您生成有效负载的方式:

    const payload = {
      postalCode: {
        postalInfo: {
          postalCode: '5282',
        },
      },
    };
    

    它应该在有效负载中有一个result 属性,因为你的reducer 期望它:

    const payload = {
      result: {
        postalInfo: {
          postalCode: '5282',
        },
      },
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2017-09-04
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多