How to reset or clear the useQuery mocks of ApolloProvider before each single test?

Viewed 1450

I am having in one describe two test functions. They both use a component with apollo mocks as this component uses useQuery. But the response from mocks for each test should be different. Now I am unable to reset or clear mocks which I propagate to the ApolloProvider. Has anyone had this kind of issue? How did you solve it?

import React from 'react'
import { render, createMocks, screen, cleanup } from 'test-utils'

import GET_DEVICES from 'src/screens/dashboard/queries/GET_DEVICES'
import Section from './Section'

describe('DashboardScreen', () => {
    const result = {
        data: {
           numDevices: 1
         }
    }
    
    const mocks = createMocks([{
        query: GET_DEVICES,
        result: result,
    }])

    afterEach(() => {
        jest.clearAllMocks() <------ THIS IS NOT SOLVING THE ISSUE
    })

    it('should load Section with expected badges', async () => {
        render(<Section />, { mocks })
   
        const badge0 = screen.getByTestId('Badge-0')
        expect(badge0).toBeInTheDocument()
        const badge1 = screen.getByTestId('Badge-1')
        expect(badge1).toBeInTheDocument()
    })

    it('should display the exclamation icon and 7 devices require attention', async () => {
        const result_local = {
          data: {
              numDevices: 4,
          }
        }

        const mocks_local = createMocks([
            {
              query: GET_DEVICES,
              result: result_local,
             }
        ])
       
        render(<Section } />, { mocks: mocks_local })

        const devicesWithActiveIssuesIcon = await screen.findByTestId('ExclamationIcon')
        expect(devicesWithActiveIssuesIcon).toBeInTheDocument()
     })
 })

The createMocks is an import and looks like this:

const createMocks = mocks =>
mocks.reduce(
  (requests, mock) => [
    ...requests,
    {
      request: {
        query: mock.query,
        variables: mock.variables
      },
      result: mock.result
    }
  ],
  []
)

It will return an object as follows:

const mocks = [
  {
    request: {
      query: GET_DEVICES,
      variables: {}
    },
    result: {
      data: {
      numDevices: 1
      },
    },
  },
]
1 Answers
Related