question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

useQuery not returning data when mock doesn't match query shape

See original GitHub issue

Intended outcome:

Test with MockedProvider receiving mocked data successfully.

related code (minimal repro):

import React from 'react'
import { render } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'

import { useQuery, gql } from '@apollo/client'
import { MockedProvider, MockedResponse } from '@apollo/client/testing'

const MY_QUERY = gql`
  query {
    __schema {
      types {
        name
        kind
        description
      }
    }
  }
`

function MyComponent() {
  const introspectionResult = useQuery(MY_QUERY)
  if (introspectionResult.loading) return <div data-testid='my-loader'>loading...</div>
  console.log(introspectionResult)
  if (!introspectionResult.data) throw new Error('should not throw!')
  return <div data-testid='my-div'>doesnt matter what to render</div>
}

test('some test', async () => {
  const mockedResponses: MockedResponse[] = [
    {
      request: { query: MY_QUERY },
      result: {
        data: {
          __schema: {
            types: [
              { name: 'bla', kind: 'yada' },
              { name: 'blabla', kind: 'yadayada' },
            ],
          },
        },
      },
    },
  ]
  const { findByTestId } = render(
    <MockedProvider mocks={mockedResponses}>
      <MyComponent />
    </MockedProvider>,
  )
  const myComponent = await findByTestId('my-div')
  expect(myComponent).toBeInTheDocument()
})

expected output:

test passes with useQuery response.data filled with the mock data, like this:

Screen Shot 2021-06-01 at 10 53 29

Actual outcome:

test fails with data: undefined even after loading finishes and there are no errors reported by the useQuery hook.

Screen Shot 2021-06-01 at 10 52 44

If you add description: whatever to each of the mocks (schema.types[n].description), the mock works fine.

My guess is that the the lack of a field asked for in the query, apparently causes some silent error, I would expect the useQuery function to return the mocked data, even without a description field.

How to reproduce the issue:

codesandbox to reproduce: https://codesandbox.io/s/sweet-bardeen-tjn9i?file=/src/MyComponent.mocks.js

steps:

  1. go to tests section, tests should pass.
  2. comment-out the “description” fields at MyComponent.mocks.js (line 12 and 17).
  3. run tests again, tests will fail.

Is this a bug or an expected behaviour I am unaware of?

if so, what do you recommend to mitigate this issue when testing? I would like to just mock the required sections of the query response for my particular test, for legibility and conciseness.

Versions

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:2
  • Comments:6

github_iconTop GitHub Comments

1reaction
barucAlmaguercommented, Jun 3, 2021

Actually i think this is the exact same bug as #8063. If a mantainer can confirm, I think it’s safe to close this duplicate issue.

Also #8063 is already marked as “fixed in pre-release”, so I guess is just a matter of time now

1reaction
ohmyskyhighcommented, Jun 2, 2021

I have similar issue, check out my previous post: https://github.com/apollographql/apollo-client/issues/7816

How I worked it around is I use useApolloClient() instead of useQueryI() Here is a brief example:

const client = useApolloClient();
client.query({query: MY_QUERY})

I think there is something wrong with useQuery hook

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mocking UseLazyQuery does not return data #6865 - GitHub
Intended outcome: After setting up MockedProvider with query mocks, uselazyquery hook should return mocked data after loading state.
Read more >
Testing React components - Apollo GraphQL Docs
Your test must execute an operation that exactly matches a mock's shape and variables to receive the associated mocked response.
Read more >
Apollo MockedProvider always returns undefined for data field ...
The mock that I supplied to the MockedProvider was a different shape than the GraphQL query, so it ended up returning nothing. Lesson:...
Read more >
Debugging Apollo GraphQL MockedProvider - Swarmia
1. Add logging with MockLink. Queries fail silently during a test case if the MockedProvider doesn't find a matching mock for the given...
Read more >
Async data made simple with React Query - Hey! I'm Tyler
As mentioned, you'll want to make the cache key unique, however if you wanted to declare a separate useQuery hook somewhere else with...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found