ReactJS / Enzyme& Jest:如何测试调用GraphQL查询或变异的函数?

时间:2017-11-20 05:26:31

标签: reactjs graphql jestjs enzyme apollo

我正在尝试Jest&用于测试ReactJs组件的酶,其中包含一个GraphQL突变以保存记录,一个graphql查询用于获取已保存的数据。在表单提交时调用Mutation,并在成功提交表单后获取重新获取查询数据。组件代码如下:

//DemoComponent.js
import import {Button,Form,Input,message} from "antd";
import { gql, graphql, compose } from "react-apollo";
import React, { Component } from "react";

class DemoComponent extends Component {
  constructor(props) {
    super(props);
    // initialize state of component
  }

  addDataHandler= (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.addData({
          variables:{
            name: values.studname,
            address: JSON.stringify(this.editor.getRaw()),
            id: this.props.id
          }
        }).then(()=>{
          message.success("Data Saved");
          this.props.studData.refetch();
        });
      }
    }
  }

  render(){
    return(
      <Form onSubmit={this.addDataHandler}>
      { /* 1 input box and 1 draft.js editor to accept Student Name and Address fields */ }
        <Button>Save</Button>
      </Form>
    );
  }
}

const addData = gql`
  mutation($name: String, $address: JSONString, $id: ID) {
    class(id: $id) {
    addData(name: $name, address: $address) {
      student{
      id
      name
      address
      }
    }
  }
}`;


export default compose(graphql(
gql`
  query DemoComponent($id: ID) {
  class(id: $id) {
    id
    classname
    student{
      edges {
      node {
        id
        name
        address
      }
      }
    }
    }
  }`,
  {
    name: "studData",
    options: ({ id }) => {
    return {
      variables: {
      id: id
      }
    };
    }
  }),
  graphql(addData, {
  name: "addData"
  })
)(Form.create()(DemoComponent));

我必须使用Jest和Enzyme测试addDataHandler(),我应该如何编写此组件的测试脚本,或者我必须重构我的代码以编写测试脚本。如何使用Jest和Enzyme编写上述组件的测试用例?

0 个答案:

没有答案