Closed
Description
Intended outcome:
I am writing a custom hook using Apollo React hooks, setting onError to do console.error
if an error occurs, but otherwise only dealing with successful data. I then want to test the error state of the custom hook using renderHook
from @testing-library/react-hooks
and MockedProvider
. I would expect onError
to be called if an error occurs, with the same value as the error
key in the useQuery
result.
Actual outcome:
onError
is never actually called
How to reproduce the issue:
The following jest test fails on the last assertion on onErrorData
import { useQuery } from '@apollo/react-hooks'
import { MockedProvider } from '@apollo/react-testing'
import { act, renderHook } from '@testing-library/react-hooks'
import gql from 'graphql-tag'
import _ from 'lodash'
import React, { useState } from 'react'
type MyQuery = {
name: string
}
const MyQueryDocument = gql`
query {
name
}
`
const useFoo = () => {
const [onErrorData, setOnErrorData] = useState()
const { data, error } = useQuery<MyQuery>(MyQueryDocument, {
onError: setOnErrorData
})
return { data, error, onErrorData }
}
test('onError should be called', async () => {
const mocks = [
{
request: {
query: MyQueryDocument,
},
error: new Error('this is an error'),
},
]
const { result } = renderHook(() => useFoo(), {
wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
<>{children}</>
</MockedProvider>
)
})
await act(() => new Promise(_.defer))
expect(result.current.data).toBeUndefined()
expect(result.current.error?.message).toBe('Network error: this is an error')
expect(result.current.onErrorData?.message).toBe('Network error: this is an error')
})
Versions
System:
OS: macOS Mojave 10.14.6
Binaries:
Node: 13.11.0 - /usr/local/bin/node
Yarn: 1.22.4 - ~/leapyear/lyalpha/node_modules/.bin/yarn
npm: 6.13.7 - /usr/local/bin/npm
Browsers:
Chrome: 80.0.3987.163
Firefox: 72.0.2
Safari: 13.1