react-native - 如何将导航参数发送到测试

标签 react-native jestjs

我正在尝试测试订阅功能,但我对 Jest 和测试还很陌生,但找不到解决方案。情况如下:

该订阅表单分为两部分,第一个部分向第二个部分发送数据。

我的问题是,如何在我的测试(第二种形式)上设置 react 导航的默认参数?

也许你会通过代码更好地理解:

我的测试结果:

TypeError: Cannot read property 'getParam' of undefined

    > 33 |       lastName: navigation.getParam('lastName', undefined),

我的测试:

describe('checking datas', () => {
  it('checking good datas', () => {
    const formUser = {
      birthday: '17/07/1992',
      country: 'France',
      refGolf: 'Bruges',
    };
    const datas = renderer.create(<SubscribeNext />).getInstance();

    expect(datas.checkValues(
      formUser.birthday,
      formUser.country,
      formUser.refGolf,
    )).toBeTruthy();
  });

我的第一个表单正在发送数据:

  toSubscribeNext() {
    const {
      navigation
    } = this.props;
    const {
      lastName,
      firstName,
      email,
      username,
      password,
      passwordCheck
    } = this.state;

    if (this.checkValues(lastName, firstName, email, username, password, passwordCheck)) {
      navigation.navigate('SubscribeNext', {
        lastName,
        firstName,
        email,
        username,
        password
      });
    }
  }

我的第二种形式正在获取它们:

export default class Subscribe extends Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    this.state = {
      lastName: navigation.getParam('lastName', undefined),
    }
  }
...

最佳答案

1 - 在您的第一个来自:

 this.props.navigation.navigate('SubscribeNext', { lastName: this.state.lastName, ... })}

2 - 在你的第二种形式中:

使用 componentWillReceiveProps 接收 props 并更新状态

...
    this.state = {lastName:''};
      ....
    componentWillReceiveProps(nextProps) {
        if (nextProps.navigation.state.params.lastName) {
          this.setState({lastName:nextProps.navigation.state.params.lastName});
        }
      }

关于react-native - 如何将导航参数发送到测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006601/

相关文章:

javascript - 如何克服 jest "Cannot access before initialization"问题?

jestjs - Redux runSaga(单元测试)错误引发局部变量未定义。如何使用 Jest 或 Sinon 模拟局部变量?

javascript - 使用 React 抽屉导航时如何处理 iOS 上的后退按钮?

javascript - Jest 在第一次失败后停止执行期望语句

javascript - ReactJS:如何更改 Material UI 中步进器标签的字体大小和 marginTop?

javascript - OnPress 不适用于 react native map 中的标记

javascript - Vue.JS/JEST - 无法模拟 Assets 引用

javascript - 开 Jest 模拟 aws-sdk ReferenceError : Cannot access before initialization

android - SoLoader : couldn't find DSO to load: libjsijniprofiler. 所以引起:dlopen failed: library "libhermes.so"

javascript - React-Native:应用程序尚未注册错误