React Native Expo项目中测试用例之间如何重置Redux状态?
解决方案
你当前的测试工具代码在模块顶层创建了Redux store单例,所有测试用例共享同一个store实例,前序测试修改的状态自然会残留到后续测试中,这是批量运行测试失败的核心原因。
修改测试工具代码,每次渲染生成全新store
调整testing-library-utils.js的逻辑,不在模块顶层初始化store,改为每次调用customRender时生成全新的干净store,从根源避免状态共享。修改后代码如下:
//This file adds a Redux Provider to a component's context when running Jest tests from test files. //This first import enables jest native, which enables some state-centric matchers import '@testing-library/jest-native/extend-expect'; import React from 'react'; import { render } from '@testing-library/react-native'; import { Provider, combineReducers, applyMiddleware, compose } from 'redux'; import ReduxThunk from 'redux-thunk'; import { createMockStore } from 'redux-test-utils'; import logBooksReducer from '../store/reducers/logBooks-reducer'; import authReducer from '../store/reducers/auth-reducer'; const composedMiddleWare = compose(applyMiddleware(ReduxThunk)); const rootReducer = combineReducers({ logBooks: logBooksReducer, auth: authReducer, }); const AllTheProviders = ({ children, customStore }) => { return <Provider store={customStore}>{children}</Provider>; }; const customRender = (ui, options = {}) => { // 支持传入自定义初始state,满足不同测试的预置状态需求 const { initialState, ...renderOptions } = options; // 每次渲染生成全新的store,无历史状态残留 const store = createMockStore(rootReducer, initialState, composedMiddleWare); return render(ui, { wrapper: (props) => <AllTheProviders {...props} customStore={store} />, ...renderOptions }); }; // re-export everything export * from '@testing-library/react-native'; // override render method export { customRender as render };
可选补充:真实Redux store的重置方案
如果你后续替换为真实Redux store而非mock库,可以给所有reducer加一个全局重置action的逻辑,无需每次新建实例:
// 定义全局重置action类型 const RESET_STORE = 'RESET_STORE'; // 每个reducer都处理该action,返回初始状态 const logBooksReducer = (state = initialLogBooksState, action) => { switch(action.type) { case RESET_STORE: return initialLogBooksState; // 其他原有逻辑 default: return state; } } // 测试时在beforeEach中触发重置即可清空状态 beforeEach(() => { store.dispatch({ type: RESET_STORE }); })
内容的提问来源于stack exchange,提问作者C.T. Bell
相关产品推荐
相关产品推荐

