测试时,如何模拟文本输入的变化?

问题描述 投票:1回答:1

我有以下代码,只有在相关数据存在的情况下才启用按钮。

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

但我的模拟似乎并不成功,因此数据仍然是空的,这反过来又意味着我的按钮仍然被禁用。能否请您帮助我解决我做错了什么?谢谢你的帮助。

请注意,下面的代码可以工作,事件按预期发射和更新。只是在编写测试时出现了问题。

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个回答
0
投票

我想你需要模拟事件(使用酶),而不是试图操作这个事件。onChange() 属性直接。

好像是一个类似的问题。https:/stackoverflow.coma3745204310610784。

试试建议的解决方案

input.simulate('change', { target: { value: 'Hello' } })
© www.soinside.com 2019 - 2024. All rights reserved.