gpt4 book ai didi

reactjs - React 组件中的 Spy 方法

转载 作者:行者123 更新时间:2023-12-02 18:58:24 25 4
gpt4 key购买 nike

我的组件有一个方法..

onUpdateProperty = (key, value) => {
this.state.formData[key] = value;
}

我想测试更改输入后是否调用此方法...

it('on update input should update formData', function () {
const wrapper = mount(<MyComp.wrappedComponent {...this.minProps} />);
const spy = spyOn(wrapper.instance(), 'onUpdateProperty');

expect(spy).not.toHaveBeenCalled();

const nameInput = wrapper.find('[name="name"]');
nameInput.simulate('change', {
target: { name: 'name', value: 'v1' },
});

wrapper.update();

// expect(spy).toHaveBeenCalledWith('name', 'v1');
expect(spy).toHaveBeenCalled();
});

wrappedComponent is because I use Mobx-react

最佳答案

我的建议是不要监视组件的内部功能,而只是测试状态

expect(wrapper.state.formData.name).toBe('v1)

如果你真的想监视它,你必须监视组件的原型(prototype)。

jest.spyOn(MyComp.wrappedComponent.prototype, 'onUpdateProperty')

关于reactjs - React 组件中的 Spy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com