【发布时间】: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