如何在每次测试之前重置或清除 ApolloProvider 的 useQuery 模拟?
Posted
技术标签:
【中文标题】如何在每次测试之前重置或清除 ApolloProvider 的 useQuery 模拟?【英文标题】:How to reset or clear the useQuery mocks of ApolloProvider before each single test? 【发布时间】:2021-04-25 21:18:19 【问题描述】:我有一个描述两个测试功能。他们都使用带有 apollo mocks 的组件,因为该组件使用 useQuery。但是模拟对每个测试的响应应该是不同的。现在我无法重置或清除我传播到 ApolloProvider 的模拟。有人遇到过这种问题吗?你是怎么解决的?
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()
)
)
createMocks 是一个导入,如下所示:
const createMocks = mocks =>
mocks.reduce(
(requests, mock) => [
...requests,
request:
query: mock.query,
variables: mock.variables
,
result: mock.result
],
[]
)
它将返回一个对象,如下所示:
const mocks = [
request:
query: GET_DEVICES,
variables:
,
result:
data:
numDevices: 1
,
,
,
]
【问题讨论】:
【参考方案1】:问题可能是用于渲染这两个组件的 ApolloProviders 共享同一个 InMemoryCache 实例。有关详细信息,请参阅以下链接。
https://github.com/benawad/apollo-mocked-provider/issues/1#issuecomment-511593398
如果是这种情况,您只需为每个测试创建新的 InMemoryCache 实例。
【讨论】:
以上是关于如何在每次测试之前重置或清除 ApolloProvider 的 useQuery 模拟?的主要内容,如果未能解决你的问题,请参考以下文章