[英]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.