如何测试组件函数内调用的Context方法的传入参数
解决方案
方案1:使用shallow内置的context配置项
Enzyme的shallow()方法支持在第二个参数传入context配置,可以同时满足mock Context和获取组件实例的需求,无需改用mount():
- 先mock Context中需要用到的方法
- 调用shallow时传入context配置
- 直接获取实例调用目标方法,断言执行结果
完整测试代码示例:
import { shallow } from 'enzyme'; import MyComponent from './MyComponent'; import MyContext from './MyContext'; describe('MyComponent 逻辑测试', () => { it('调用myFunction时会向context的otherFunction传入正确参数', () => { // mock Context方法 const mockOtherFunction = jest.fn(); const mockContext = { otherFunction: mockOtherFunction }; // shallow渲染时传入context const wrapper = shallow(<MyComponent />, { context: mockContext }); // 获取实例调用目标方法 const componentInstance = wrapper.instance(); componentInstance.myFunction(); // 断言调用符合预期 expect(mockOtherFunction).toHaveBeenCalledTimes(1); expect(mockOtherFunction).toHaveBeenCalledWith('shouldBecorrectValue'); }); });
方案2:临时修改Context运行时值(兼容低版本Enzyme)
如果你的Enzyme版本较低,方案1无法正常生效,可以直接在测试侧临时修改Context的运行时值,测试完成后还原即可,完全不需要修改业务代码:
import { shallow } from 'enzyme'; import MyComponent from './MyComponent'; import MyContext from './MyContext'; describe('MyComponent 逻辑测试', () => { // 保存Context原始值 let originContextValue; const mockOtherFunction = jest.fn(); beforeEach(() => { originContextValue = MyContext._currentValue; // 替换为mock值 MyContext._currentValue = { otherFunction: mockOtherFunction }; }); afterEach(() => { // 还原原始值,避免影响其他用例 MyContext._currentValue = originContextValue; jest.clearAllMocks(); }); it('调用myFunction时会向context的otherFunction传入正确参数', () => { const wrapper = shallow(<MyComponent />); const componentInstance = wrapper.instance(); componentInstance.myFunction(); expect(mockOtherFunction).toHaveBeenCalledTimes(1); expect(mockOtherFunction).toHaveBeenCalledWith('shouldBecorrectValue'); }); });
注意事项
- 如果你的组件使用
Context.Consumer而非static contextType消费Context,可以在shallow的options中传入wrappingComponent: MyContext.Provider和wrappingComponentProps: {{ value: mockContext }},再调用wrapper.dive().instance()即可拿到目标组件实例。
内容的提问来源于stack exchange,提问作者user6490576
相关产品推荐
相关产品推荐

