【问题标题】:Test for react async action creator - undefined data测试反应异步动作创建者 - 未定义的数据
【发布时间】:2018-12-20 20:33:28
【问题描述】:

我有以下动作和测试用例 - 当我运行这个测试时(开玩笑) - 我看到 TypeError: Cannot read property 'data' of undefined in action creator, 不确定这里缺少什么?我正在提供预期的 mockData。是因为这里嵌套了一个异步吗?但我正在使用 `.then 但它仍然失败。

Action creator:

    export const getUser = ({
      uname,
      apiendpoint,
    }) => {
      const arguments = {};


      return async (dispatch) => {
        await axiosHelper({ ---> this will return axios.get
          arguments,
          path: `${apiendpoint}/${uname}`,
          dispatch,
        }).then(async ({ data, headers }) => { -- getting error at this line.
          dispatch({ type: GET_USER, payload: data });
          dispatch({ type: GET_NUMBEROFUSERS, payload: headers });
        });
      };
    };

Test:

    describe('Get User Action', () => {
      let store;
      const middlewares = [thunk];
      const mockStore = configureStore(middlewares);
      beforeEach(() => {
        store = mockStore({
          data: [],
        });
      });

      afterEach(() => {
        fetchMock.reset();
        fetchMock.restore();
      })

       const arguments = {
        uname: 'user123',
        apiendpoint: 'test',
      };
      const url = 'https://www.localhost.com/blah/blah';

      it('should get a User', () => {
        fetchMock
          .getOnce(url, {
            data: mockData, -->external mock js file with user data {}
            headers: {
              'content-type': 'application/json'
            }
          });

        const expectedActions = [
          {
            type: 'GET_USER',
            data: mockData
          },
          { type: 'GET_NUMBEROFUSERS' }
        ];


        return store.dispatch(actions.getUser(arguments)).then(() => {
          expect(store.getActions()).toEqual(expectedActions);
        });

      });

【问题讨论】:

    标签: react-redux jestjs redux-mock-store


    【解决方案1】:

    您在同一个函数上使用await AND then(例如axiosHelper)。

    这是错误的用法,会导致undefined的很多错误。 您可以使用回调函数 .then() await,但不能使用两个或全部。

    我建议观看一些关于 async/await 的教程/解释,因为了解 Promise 是什么非常重要。

    在你的 cas 中发生的事情是 axiosHelper 被执行了 2 次,因为如果它完成了 then-part 将会启动,但在完全相同的时间(因为它是异步的)await 完成和代码-执行继续父流程。这带来了竞争条件,正如我所说,将导致undefined,因为您执行相同的逻辑两次或更多次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2019-07-22
      • 2016-10-16
      • 2017-12-09
      相关资源
      最近更新 更多