Created
October 8, 2018 10:57
-
-
Save corzani/8b4746a4c19b0621aaa4ae796e0c880a to your computer and use it in GitHub Desktop.
Apollo React MockedProvider Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import wait from 'waait'; | |
import {MockedProvider} from "react-apollo/test-utils"; | |
import TestRenderer from 'react-test-renderer'; | |
import {Query} from "react-apollo"; | |
import gql from 'graphql-tag'; | |
const A_QUERY = gql` | |
query getSomething($name: String) { | |
something(name: $name) { | |
name | |
} | |
} | |
`; | |
const mockSuccessfullReq = { | |
request: { | |
query: A_QUERY, | |
variables: {name: 'something'} | |
}, | |
result: {data: {something: {name: 'My own name'}}} | |
}; | |
const mockFailedRequest = { | |
request: { | |
query: gql`{ C { d } }`, | |
variables: {b: 'something'} | |
}, | |
error: new Error("Problems here") | |
}; | |
const Loading = () => (<p>Loading...</p>); | |
const ErrorMessage = ({msg}) => (<p>{msg}</p>); | |
const Output = ({msg}) => (<p>{msg}</p>); | |
const ApolloQuery = ({query, variables}) => ( | |
<Query query={query} variables={variables} errorPolicy="all"> | |
{({loading, error, data}) => { | |
if (loading) return <Loading/>; | |
if (error) return <ErrorMessage msg={error.toString()}/>; | |
return ( | |
<Output msg={data.something.name}/> | |
); | |
}} | |
</Query> | |
); | |
describe('Apollo React Query', function () { | |
it('should show the Output element when the request is correct', async () => { | |
const {query, variables} = mockSuccessfullReq.request; | |
const result = TestRenderer.create( | |
<MockedProvider mocks={[mockSuccessfullReq]} addTypename={false}> | |
<ApolloQuery query={query} variables={variables}/> | |
</MockedProvider> | |
); | |
await wait(0); // wait for response | |
const resultInstance = result.root; | |
console.log(resultInstance.toString()); | |
expect(resultInstance.findByType(Output).props.msg).toEqual('My own name'); | |
}); | |
it('should handle an unsuccessful response showing the error element', async () => { | |
const {query, variables} = mockFailedRequest.request; | |
const result = TestRenderer.create( | |
<MockedProvider mocks={[mockFailedRequest]} addTypename={false}> | |
<ApolloQuery query={query} variables={variables}/> | |
</MockedProvider> | |
); | |
await wait(0); | |
const resultInstance = result.root; | |
expect(resultInstance.findByType(ErrorMessage).props.msg).toEqual("Error: Network error: Problems here"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment