redux-mock-store的存储状态在分派操作后未更新

g6ll5ycj  于 2023-06-06  发布在  其他
关注(0)|答案(2)|浏览(194)

我有一个记录器中间件,它可以显示将要调度的操作和下一个状态。
我正在为我的操作编写测试,并在模拟存储中分派操作。这些成功地分派,但是模拟存储状态没有被更新(如前面提到的日志所示)。
请注意,我使用的是redux-mock-store。

//authActionTest.js

it('creates LOGIN_SUCCESS when successful login has occured', ()=>{

//array of expected actions to be dispatched.
const expectedActions = [
  { type: constants.LOGIN_REQUEST },
  { type: 'LOGIN_SUCCESS',
            payload: {
                uid: '123abc',
                role: 'clinician'
    }}
]
const store = mockStore({ auth : {} })

return store.dispatch(actions.loginUser('abc@123.com', 'password123'))
expect(store.getActions()).toEqual(expectedActions)
})

记录器显示以下内容:

//logger
dispatching({ type: 'LOGIN_REQUEST })
next state { auth: {} }
dispatching({ type: 'LOGIN_SUCCESS',
   payload: { uid: 123,
              role: 'clinician'
          })
next state { auth: {} }
dly7yett

dly7yett1#

您正在尝试测试异步操作。
为了回答这个问题,我们可以遵循redux文档的建议。

describe('async actions', () => {
    afterEach(() => {
      nock.cleanAll();
    });
    it('creates LOGIN_SUCCESS on successful login', () => {
      nock('http://example.com/')
        .get('/login')
        .reply(200, payload: { uid: 123, role: 'clinician' });

      const expectedActions = [
        { type: types.LOGIN_REQUEST },
        { type: types.LOGIN_SUCCESS, payload: { uid: 123, role: 'clinician' } },
      ];
      const store = mockStore({ auth: {} });

      return store.dispatch(actions.loginUser())
        .then(() => { // return of async actions
          expect(store.getActions()).toEqual(expectedActions);
        });
    });
  });

您可能需要对上述代码进行一些修改才能使其工作。
如果你正在使用axios,我会建议使用moxios包而不是nock。

fsi0uk1n

fsi0uk1n2#

来自redux-mock-store文档:
请注意,这个库是为了测试动作相关的逻辑而设计的,而不是reducer相关的逻辑。换句话说,它不会更新Redux商店。
看看redux-mock-store包的getState()方法,mockStore函数传入的状态对象没有任何操作就返回了。
你有一些测试redux动作和reducer的选择。

相关问题