【问题标题】:How to simulate text input onchange when testing测试时如何模拟文本输入onchange
【发布时间】:2020-10-04 04:55:53
【问题描述】:

我有以下代码,如果存在相关数据,我只启用一个按钮。

我试图通过伪造输入字段的更改来测试这一点,以便相关数据可用。

但我的模拟似乎不起作用,因此数据仍然为空,这反过来意味着我的按钮仍然处于禁用状态。我可以就我做错的事情寻求帮助吗?谢谢你。

请注意,以下代码适用于事件按预期触发并更新的情况。只需发出书面测试。

const [code1, setCode1] = useState(''); 

const cannotPress = () => !(code1);

const handleFieldChange = (event, updater) => {
    updater(event.target.value);
};

// in test, trying to simulate a value entered in this input so that the event fires and 
// updates code1's value thus making cannotPress=false. This would enable the button and pass test.
<input id="code1" value={code1} onChange={event => handleFieldChange(event, setCode1)} />
<button id='btn type="submit" disabled={cannotPress()} onClick={() => doSomething()}>Submit</button>

测试

describe('tests', () => {
  const wrapper = shallow(<MyApp info={info} />);
  it('simple test', () => {
    const btn = wrapper.find('button#btn'); // able to find button
    const input = wrapper.find('input#code1'); // able to find input (tested by placing in default values)
    console.log(input.props().value); // prints nothing as expected
    input.instance().props.onChange(({ target: { value: 'some fake data' } })); // expecting the event to trigger and change value for code1.
    console.log(input.props().value); // ISSUE: expected to print 'some fake data' but still empty.
    expect(btn.prop('disabled')).toBe(false); // fails cos input has no value thus disabled is still true
  });
});

【问题讨论】:

    标签: javascript reactjs enzyme


    【解决方案1】:

    我认为您需要模拟事件(使用酶),而不是尝试直接操纵 onChange() 属性。

    似乎与以下类似的问题: https://stackoverflow.com/a/37452043/10610784

    尝试建议的解决方案

    input.simulate('change', { target: { value: 'Hello' } })
    

    【讨论】:

    • 运行您建议的命令后输入的值仍然为空的结果相同。
    • 我感觉这个值可能不是空的,而是你对元素的引用已经过时了。在上面的input.simulate() 命令之后,执行console.log(wrapper.find('input#code1').props().value)。如果该值仍然为空,则可以尝试相同的操作,但使用之前尝试模拟事件的方式(使用 props.onChange() )
    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2020-12-20
    • 2021-02-09
    相关资源
    最近更新 更多