I have written simple react-apollo component which uses graphql query to retrieve data from schema. On execution component works fine but, when I am writing test case for this component using jest framework together with MockedProvider(i.e. component of react-apollo/test-utils). I am unable to populate component with data. I had refered this article on MockedProvider: https://paradite.com/2017/11/16/test-react-apollo-components-enzyme-examples/
my component and test script is as below:
//MyComponent.js
import React, { Component } from "react";
import { gql, graphql, compose } from "react-apollo";
export class MyComp extends Component {
render() {
console.log("data",this.props);
return (
<div>Hello welcome {this.props.msg}
{!this.props.data.loading && this.props.data.person.edges.map((person,i)=>(
<p key={i}>{person.node.name}</p>
)
)}
</div>
);
}
}
export const PERSON_QUERY = gql`query Info {
person{
edges{
node{
id
name
__typename
}
__typename
}
__typename
}
}`;
export default compose(graphql(PERSON_QUERY,{}))(MyComp);
//MyComponent.test.js
import React from 'react';
import { configure, mount } from 'enzyme';
import toJSON from 'enzyme-to-json';
import { MockedProvider } from 'react-apollo/test-utils';
import { addTypenameToDocument } from 'apollo-client';
import { gql, graphql, compose } from "react-apollo";
import MyComponent,{MyComp, PERSON_QUERY} from 'components/MyComponent';
import Adapter from 'enzyme-adapter-react-15';
import {store} from "stores/store";
configure({adapter: new Adapter()});
const data1 = {
person: {
edges: [
{
node: {
id: "00000000-0002-972",
name: "Magic Mad",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "000-0001-972",
name: "Donald Durm",
__typename: "Person"
},
__typename: "PersonEdge"
},
{
node: {
id: "00-0000-fccd3",
name: "Peter Hogwarts",
__typename: "Person"
},
__typename: "PersonEdge"
}
],
__typename: "PersonConnection"
}
};
describe("MockedProvider",()=>{
test("Load with data",()=>{
const wrap = mount(<MockedProvider mocks={[
{
request: {
query: addTypenameToDocument(PERSON_QUERY)
},
result: { data: data1 }
}
]}>
<MyComponent msg={"2018"}/>
</MockedProvider>);
console.log("Mock",wrap.props());
console.log("html",wrap.html());
wrap.update();
});
});
Author of the post here.
A number of issues that I can see quite easily:
where
data2is not defined, I think you meandata1.Also, your mock data
data1has adataproperty, which is wrong, because the result object already has adataproperty, you should remove it fromdata1and exposepersonproperty directly:Another thing you should probably know, in case this still does not solve your issue, is that you can log the
wrapvariable to see the mocks and check if they match what you want:You can try to debug from there.