********************* Обновлено **************************** *****************
У меня есть компонент DialogBox, который я пытаюсь протестировать. Я пытаюсь установить опору «значение» дочернего компонента (TextInput) внутри DialogBox. Я перепробовал почти все, но ничего не работает. Кто-нибудь может мне помочь?
test('input type returns a text', () => {
const okPressFunction = jest.fn()
const obj = (
shallow(
<DialogBox
title='random title'
message = {lorem}
type='input'
isVisible
onOkPress = {okPressFunction}
onRequestClose = {noop}
/>
)
)
// obj.dive().find('TextInput').setProps({ value: 'hi' })
// obj.update()
// console.info(obj.dive().find('TextInput').prop('value'))
obj.find('TextInput').simulate('change', {
target: { value: 'hello' },
})
obj.update()
console.info(obj.dive().find('TextInput').prop('value'))
})
})
Дамп console.info (obj.html ()):
<Component
transparent = {true}
animationType = "fade"
visible = {true}
onRequestClose = {[(Function: noop)]}
hardwareAccelerated = {false}
>
<View
style = {{
backgroundColor: "#33333340",
width: "100%",
height: "100%",
justifyContent: "center",
alignItems: "center",
}}
>
<View
style = {{
backgroundColor: "white",
width: "80%",
borderRadius: 2,
borderColor: "#a4a4a4",
flexDirection: "column",
paddingHorizontal: 7,
}}
>
<View stlye = {{ flexDirection: "column", justifyContent: "flex-start" }}>
<H3 style = {{ fontWeight: "bold" }} if = {true}>
random title
</H3>
<Text style = {{}} if = {true}>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos
doloribus, eos porro sed velit sunt. Maiores ipsa, voluptatum ad
explicabo aut rem aperiam animi consequuntur libero eveniet sed,
voluptatem velit?
</Text>
</View>
<TextInput
noSpacing = {true}
placeholder = "input here..."
name = "input"
onChangeText = {[(Function: onChangeText)]}
value = {null}
icon = {null}
style = {{}}
hasFloatingLabel = {true}
numberOfLines = {1}
isPassword = {false}
if = {true}
/>
<View style = {{ flexDirection: "row", justifyContent: "flex-end" }}>
<Button
type = "text"
title = "cancel"
onPress = {null}
icon = {null}
iconPosition = "right"
iconProps = {{}}
isDisabled = {false}
isLoading = {false}
size = "medium"
style = {{}}
textContainerStyles = {{}}
if = {true}
/>
<View style = {{ flexDirection: "row", justifyContent: "flex-end" }}>
<Button
type = "text"
title = "action"
onPress = {[(Function: onPress)]}
icon = {null}
iconPosition = "right"
iconProps = {{}}
isDisabled = {false}
isLoading = {false}
size = "medium"
style = {{}}
textContainerStyles = {{}}
if = {true}
/>
</View>
</View>
</View>
</View>
</Component>
Я тестирую сценарий тестирования пользовательского интерфейса, в котором пользователь сначала вводит значение в текстовом поле ввода, а после нажатия последней кнопки («действие») входное значение возвращается, как в функции обратного вызова. Но сначала мне нужно установить значение текстового ввода. У меня есть одна официальная документация и много обсуждений без какой-либо значимой помощи.
Код диалогового окна:
export class DialogBox extends PureComponent {
state = {
textInput: null,
}
okButton = (
<View style = {styles.buttons}>
<Button
type = "text"
title = {t('action')}
onPress = {() => {
this.props.onOkPress(this.state.textInput)
this.setState({ textInput: null })
}}
/>
</View>
)
cancelButton = (
<Button
type = "text"
title = {t('cancel')}
onPress = {this.props.onCancelPress}
/>
)
confirmButtons = (
<View style = {styles.buttons}>
{this.cancelButton}
{this.okButton}
</View>
)
inputButtons = (
<Fragment>
<TextInput
noSpacing
placeholder = "input here..."
name = "input"
onChangeText = {(text) => this.setState({ textInput: text })}
/>
{this.confirmButtons}
</Fragment>
)
renderButtons (type) {
switch (type) {
case 'confirm':
return this.confirmButtons
case 'alert':
return this.okButton
case 'input':
return this.inputButtons
default:
return this.okButton
}
}
render () {
const {
title,
message,
isVisible,
type,
onRequestClose,
} = this.props
return (
<Modal
transparent
animationType = "fade"
visible = {isVisible}
onRequestClose = {onRequestClose}
>
<View style = {styles.container}>
<View style = {styles.alertContainer}>
<View stlye = {styles.textContainer}>
<H3 style = {styles.title}>{title}</H3>
<Text>{message}</Text>
</View>
{this.renderButtons(type)}
</View>
</View>
</Modal>
)
}
}
в теме. Дай мне минуту
Готово. Я обновил свой пост



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Эта почта от разработчика Airbnb рекомендует избегать использования simulate и напрямую вызывать реквизиты.
Применяя этот подход:
test('input type returns a text', () => {
const okPressFunction = jest.fn()
const obj = (
shallow(
<DialogBox
title='random title'
message = {lorem}
type='input'
isVisible
onOkPress = {okPressFunction}
onRequestClose = {noop}
/>
)
)
obj.find('TextInput').props().onChangeText('hello');
obj.find('Button').at(1).props().onPress();
expect(okPressFunction).toHaveBeenCalledWith('hello'); // SUCCESS
});
Большое спасибо! Это было очень полезно!
wrapper.props().valueне сообщает вам состояние ввода, он передает реквизиты, переданные компоненту, поэтому ваш вызов.simulateна самом деле не делает ничего, что изменит реквизиты. опубликуйте свой кодDialogueBox, иначе сказать сложно.