I am trying hands on Jest & Enzyme to test ReactJs components which contains one GraphQL mutation to save record and one graphql query to fetch saved data. Mutation gets called on form submission and query data gets refetch after completion of successful form submission. Component code is as followed:
//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));
I have to test addDataHandler() using Jest and Enzyme, How should i write test script for this component or I have to restructure my code for writing test scripts. How to write test cases for above component using Jest and Enzyme?