[英]How to set a value to an input text element of a stateless function inside a Jest test
由于我使用的是无状态函数,因此我无法使用它:
wrapper.find('input').instance().value = 'some text'
这也已弃用:
wrapper.find('input').node.value = 'some text'
你知道什么是实现这一目标的正确方法吗? 我对测试并不陌生,如果我错了,请纠正我:
我使用const component = mount(<PostMessages/>)
创建了组件。
我的目标文本输入是这样的: const input = component.find('input')
。
这是我缺少的平静。
我的组件:
const PostMessage = props => {
let inputText;
const onKeypressHandler = (e) => {
if (e.key === 'Enter') {
if (inputText.value) {
sendMessage(inputText.value);
clearInput();
}
}
}
const clearInput = () => {
inputText.value = '';
}
const setRef = (input) => {
if (input) {
inputText = input;
inputText.focus();
}
}
const stringIsBlank = (str) => {
return (!str || /^\s*$/.test(str));
}
const formatMessage = (message) => {
return stringIsBlank(message) ? false : message.trim();
}
const sendMessage = (message) => {
const formatedMessage = formatMessage(message);
if(formatedMessage) {
props.send(formatedMessage);
}
}
return (
<PostMessageStyle>
<input type="text"
placeholder="Your message..."
onKeyPress={onKeypressHandler}
ref={input => setRef(input)}
/>
<button onClick={sendMessage}>Send</button>
</PostMessageStyle>
)
};
您正确执行wrapper.find('input').instance().value = 'some text'
但您还需要在输入上触发更改事件。 你可以这样做:
const myInput = wrapper.find('input');
myInput.instance().value = 'some text';
myInput.simulate('change');
或者,您也可以直接使用如下值触发更改事件:
wrapper.find('input').simulate('change', { target: { value: 'some text' } });
这仅适用于组件,不适用于功能。 没有办法做到这一点,因为无状态组件没有方法。 来自图书馆的创建者:
答案是您不测试该功能——您只测试组件,并为所有代码路径添加测试。 你不能直接测试,也不应该。
如果要测试它,则必须将其转换为组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.