Enzyme测试中无法更新Office Fabric UI TextField值的问题
解决Office UI Fabric React TextField的Enzyme/Jest测试值更新问题
我明白你遇到的问题了——明明触发了onChange,但组件状态就是没更新,测试卡在这里确实头疼。问题的根源在于Office UI Fabric的TextField的onChange签名和Enzyme默认的simulate传参方式不匹配。
为什么原来的写法不生效?
你的组件里onCommentChange接收两个参数:事件对象和新的输入值,但你用simulate('change', { target: { value: 'test value' } })时,只传递了事件对象作为第一个参数,第二个参数newValue会是undefined。这就导致setComments(undefined),状态根本没更新成你期望的文本,按钮自然还是禁用状态。
两种可行的解决方案
方案1:直接调用onChange props(推荐)
绕过Enzyme的simulate,直接调用TextField暴露的onChange方法,手动传递正确的参数:
it('should enable the submit button when the user enters a comment', () => { const wrapper = shallow(<FeedbackForm {...mockProps} />); const commentBox = wrapper.find(TextField); const submitButton = wrapper.find('[type="submit"]'); // 直接调用onChange,传递空事件对象和目标值 commentBox.props().onChange({}, 'test value'); // 刷新组件以获取最新状态 wrapper.update(); expect(submitButton.is('[disabled]')).toBe(false); });
方案2:给simulate传递第二个参数
如果你更倾向于用simulate,可以给它加第二个参数作为newValue——Enzyme的simulate会把后续参数直接传给事件处理函数:
it('should enable the submit button when the user enters a comment', () => { const wrapper = shallow(<FeedbackForm {...mockProps} />); const commentBox = wrapper.find(TextField); const submitButton = wrapper.find('[type="submit"]'); // 第一个参数是事件对象,第二个是newValue commentBox.simulate('change', {}, 'test value'); wrapper.update(); expect(submitButton.is('[disabled]')).toBe(false); });
额外提示
用shallow渲染时,组件状态更新后记得调用wrapper.update(),确保Enzyme能拿到最新的组件快照,避免因为渲染滞后导致断言失败。
内容的提问来源于stack exchange,提问作者John Pham
相关产品推荐
相关产品推荐

