React Native中用Enzyme测试componentDidMount是否调用autoLogin Redux Action
测试React Native组件componentDidMount中Redux Action的调用
我懂你现在的困扰:想确认SplashScreen的componentDidMount生命周期里,是否正确触发了autoLogin这个Redux Action,但不知道怎么验证这个dispatch操作是否真的执行了。下面给你梳理具体的解决思路和修正后的代码:
核心解决思路
要验证Redux Action的调用,我们需要用redux-mock-store跟踪store的dispatch记录,同时确保组件完成挂载以触发componentDidMount生命周期。
修正后的测试代码
先确保你导入了必要的依赖和目标Action,然后按以下方式编写测试:
import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { shallow } from 'enzyme'; import SplashScreen from './index'; import { autoLogin } from './your-action-path'; // 替换成你的action实际路径 const mockStore = configureMockStore([thunk]); describe('SplashScreen Component', () => { it('dispatches autoLogin exactly once on mount', () => { // 初始化mock store并保留引用,方便后续获取dispatch记录 const store = mockStore({}); // 渲染组件并dive到实际的SplashScreen(跳过connect高阶组件) shallow(<SplashScreen store={store} />).dive(); // 获取store中所有被dispatch的actions const dispatchedActions = store.getActions(); // 验证是否触发了预期的autoLogin action expect(dispatchedActions.length).toBe(1); expect(dispatchedActions[0]).toEqual(autoLogin()); }); });
另一种更直接的测试方式(针对mapDispatchToProps绑定场景)
如果你的SplashScreen是通过mapDispatchToProps把autoLogin绑定为组件props的(如下方示例),那可以直接mock这个props方法来验证,不需要依赖mock store,测试更聚焦组件本身:
组件连接代码示例
import { connect } from 'react-redux'; import { autoLogin } from './actions'; class SplashScreen extends Component { componentDidMount() { this.props.autoLogin(); // 调用props中的autoLogin方法 } } const mapDispatchToProps = { autoLogin }; export default connect(null, mapDispatchToProps)(SplashScreen);
对应的测试代码
import { shallow } from 'enzyme'; import SplashScreen from './index'; it('calls autoLogin prop once on component mount', () => { // 创建一个mock函数来跟踪调用情况 const mockAutoLogin = jest.fn(); // 渲染组件并传入mock的autoLogin props shallow(<SplashScreen autoLogin={mockAutoLogin} />); // 验证mock函数被调用了一次 expect(mockAutoLogin).toHaveBeenCalledTimes(1); });
为什么之前的代码没效果?
你之前的代码仅完成了组件渲染,但没有对store的dispatch记录做断言,也没有跟踪Action的调用情况。通过store.getActions()可以拿到所有被触发的Action对象,再和预期的autoLogin()返回值对比,就能确认Action是否被正确dispatch了。
内容的提问来源于stack exchange,提问作者Anders Ekman
相关产品推荐
相关产品推荐

