简体   繁体   English

编写测试以更改子组件的属性

[英]write a test to change prop of a child component

*********************Updated********************************************* *********************更新**************************** *****************

I have a DialogBox component that I am trying to test out. 我有一个要测试的DialogBox组件。 I am trying to set the 'value' prop of a child component(TextInput) inside the DialogBox. 我正在尝试在DialogBox中设置子组件(TextInput)的'value'属性。 I have tried almost everything but nothing seems to work. 我已经尝试了几乎所有内容,但似乎没有任何效果。 Can some one help me? 有人能帮我吗?

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.log(obj.dive().find('TextInput').prop('value'))
obj.find('TextInput').simulate('change', {
  target: { value: 'hello' },
})
obj.update()
console.log(obj.dive().find('TextInput').prop('value'))
  })
})

The console.log(obj.html()) dump is: console.log(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>

I am testing a ui test scenario in which a user first inputs a value in text Input and once clicks on the last button ('action') the input value is returned as in a callback function. 我正在测试一个ui测试方案,在该方案中,用户首先在文本Input中输入一个值,然后单击最后一个按钮(“操作”),然后返回输入值,就像在回调函数中一样。 But, first I need to set value of the text Input. 但是,首先我需要设置文本Input的值。 I have one through official docs and many threads with no meaningful help. 我有一个通过官方文档和许多线程没有有意义的帮助。

Dialog box code: 对话框代码:

   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>
    )
  }
}

This post from an Airbnb dev recommends avoiding simulate and invoking the props directly. Airbnb开发人员的这篇文章建议避免simulate并直接调用道具。

Applying that approach: 应用该方法:

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM