代码之家  ›  专栏  ›  技术社区  ›  Oscar Franco

Jest Redux,模拟出口发货

  •  0
  • Oscar Franco  · 技术社区  · 7 年前

    我有一个使用redux和connect(react redux)的react本机项目,我想用文本说明组件在安装时调用了正确的操作。

    问题是我没有遵循传统的Redux结构,所以我没有使用mapDispatchToprops,而是导出了我的商店实例,并直接从中获取调度。

    我的商店:

    declare const window: any;
    
    import { default as auth } from './reducer/auth.reducer';
    import { default as request } from './reducer/request.reducer';
    
    const appReducer = combineReducers({
      auth,
      request
    });
    
    const initialState = {};
    
    const complexCompose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
    
    const enhancer = complexCompose(applyMiddleware(thunk), autoRehydrate());
    
    const store = createStore(appReducer, initialState, enhancer);
    
    // To purge the store
    // persistStore(store, { storage: AsyncStorage }).purge();
    persistStore(store, { storage: AsyncStorage as any, blacklist: [] });
    
    export const dispatch = store.dispatch;
    export const getState = store.getState;
    
    export default store;
    

    我行动的一个例子:

    import { ActionPhase } from '../model/Enums';
    import { ActionType } from '../model/ActionType';
    import api from './api';
    import store, { dispatch } from '../store';
    import uuid from 'uuid';
    
    export type AuthReduxAction =
      | { type: ActionType.LOGIN, phase: ActionPhase, transactionId: string, payload ?: { user: any; token: any; }; };
    
    export function login(email: string, password: string) {
      const transactionId = uuid();
      dispatch({ type: ActionType.LOGIN, phase: ActionPhase.START, transactionId });
      return api.login(email, password)
        .then((res) => {
          store.dispatch({ type: ActionType.LOGIN, phase: ActionPhase.SUCCESS, transactionId });
          return res;
        })
        .catch((err) => {
          store.dispatch({ type: ActionType.LOGIN, phase: ActionPhase.FAIL, transactionId });
        });
    }
    

    我的测试:

    import React from 'react';
    import configureStore from 'redux-mock-store';
    
    import { LoginContainer } from '../../src/container';
    import { shallow } from 'enzyme';
    
    describe('Test Login Container', () => {
      const store = mockStore(initialState);
      // jest.doMock('../../src/store', () => ({
      //   dispatch: store.dispatch
      // }), { virtual: true });
      // globalStore.dispatch = store.dispatch; <-- the thing that doesn't work
    
      it('Mount', () => {
        const wrapper = shallow(<LoginContainer navigation={navigation}/>,
          {
            context: { store }
          }
        );
    
        expect(wrapper.dive()).toMatchSnapshot();
        expect(store.getActions()).toMatchSnapshot(); // <- this is empty
      });
    });
    

    问题是:当我检查快照中调度到存储的操作时,它是空的,而我希望看到我的登录操作被调度,有什么建议吗?

    0 回复  |  直到 7 年前
    推荐文章