如何在玩笑中测试日期选择器组件

时间:2018-12-06 15:39:03

标签: javascript jestjs enzyme

我对React和Jest完全陌生。 我有一个带有两个日期字段和按钮的React组件,我想使用Jest框架进行测试。正如我所说,如果有人可以举一个例子,我在React和Jest方面都是全新的。

这是我的组件:

import React, { Component } from 'react';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Container, Col, Form, FormGroup, Label, Input, Button, } from 'reactstrap';

class Aquaculturedatepicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dateFrom: '',
      dateTo: '',
      loading: false,
    };
  }

  handleFirstDayChange = (dateFrom) => {
    this.setState({ dateFrom });

  }

  handleSecondDayChange = (dateTo) => {
    this.setState({ dateTo });
  }

  onSubmit = (e) => {
    e.preventDefault();
    const dateFrom = this.state.dateFrom
    const dateTo = this.state.dateTo
    this.setState({ loading: true })
    this.props.onDateChange(dateFrom, dateTo);
  }

  render() {
    // console.log('hello', this.state.dateFrom)
    // console.log('hello', this.state.dateTo)
    const { dateFrom, dateTo } = this.state;
    return (<Container className="Datepickerfrom" style={{ width: "1000px", paddingTop: "2px", paddingBottom: "60px" }}>
              <Form onSubmit={this.onSubmit.bind(this)} inline>
                  <Col>
                  <FormGroup>
                      <Label style={{ paddingRight: "5px", margin: "0.2", fontSize: "20px" }}>Date From</Label>
                      <DayPickerInput value={dateFrom} onDayChange={this.handleFirstDayChange} inputProps={{ required: false }} />
                  </FormGroup>
                  </Col>
                  <Col>
                  <FormGroup>
                      <Label style={{ paddingRight: "5px", margin: "0.2em", fontSize: "20px" }}>Date To</Label>
                      <DayPickerInput value={dateTo} onDayChange={this.handleSecondDayChange} inputProps={{ required: false }} />
                  </FormGroup>
                  </Col>
                  <Button className="btn-lg btn-primary" style={{ padding: "6px", margin: "0.2em", fontSize: "20px", backgroundColor: "#008CBA", border: "none" }}>
                      <i className="far fa-calendar-alt"></i> Submit
                  </Button>
              </Form>
          </Container>)
  }
}
export default Aquaculturedatepicker;

1 个答案:

答案 0 :(得分:0)

因此,您需要测试的是可以在DayPicker组件中输入值,并使用在提交时输入的值来调用onDateChange

const onDateChange = jest.fn()
const component = shallow(<Aquaculturedatepicker onDateChange={onDateChange} />) 

const dayPickers = component.find('DayPickerInput')
dayPickers.at(0).prop('onDayChange')('date1')
dayPickers.at(1).prop('onDayChange')('date2')


component.find('Form').simulate('submit')
expect(onDateChange).toHaveBeenCalledWith('date1', 'date2')