我如何测试我的React Native组件的功能?

时间:2017-12-27 15:53:43

标签: javascript react-native

我有以下组件......

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {
  Button,
  StyleSheet,
  Text,
  View,
  TextInput
} from 'react-native';
import BooksViewModel from './books-viewmodel'

class BooksComponent extends Component {

  constructor(props) {
    debugger;
    super(props);
    this.state = BooksViewModel.init();
  }

  componentDidMount() {
    this.props.load();
  }

  saveBook() {
    this.props.save(this.state).then(() => {
      this.setState(BooksViewModel.init());
    });
  }

  render() {
    return (
      <View>

        {
          this.props.booksListViewModel.map((book) => {
            return (<Text key={book.ISBN}>{book.ISBN}</Text>);
          })
        }

        <Text>Name :</Text>
        <TextInput
          style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 100}}
          onChangeText={(text) => this.setState({name: text})}
          value={this.state.name}
        />

        <Text>ISBN :</Text>
        <TextInput
          style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 100}}
          onChangeText={(text) => this.setState({ISBN: text})}
          value={this.state.ISBN}
        />

        <Button
          title="Save"
          onPress={() => this.saveBook()}/>
      </View>
    );
  }
}

export default connect( (state) =>  { return state;} , BooksViewModel.connect)(BooksComponent)

我有测试......

   const booksComponent = renderer.create(<Provider store={store}><BooksComponent/></Provider>).getInstance();

我希望能够做到以下......

booksComponent.setState({name:'myName'});
booksComponent.setState({ISBN:'myText'});
booksComponent.saveBook();
expect(booksComponent.props.booksListViewModel).toBe({message:success});

但我无法找到如何调用setState以及如此调用组件上的函数。有没有人有任何想法?

0 个答案:

没有答案