小编Ant*_*ton的帖子

用 Jest 模拟 ApolloClient 的 client.query 方法

2020 年 1 月 22 日更新

@slideshowp2 的解决方案是正确的,但由于这个 TypeError,我根本无法让它工作:

类型错误:无法读取未定义的属性“查询”

好吧,结果是我的玩笑配置已经resetMocks: true设置了。我把它去掉后,测试确实通过了。(虽然我不知道为什么)


原问题:

我需要使用 Apollo Client 在 React 组件之外的辅助函数中执行 graphql 查询,经过一番尝试和错误后,我采用了这种方法,该方法按预期工作:

安装程序.ts

export const setupApi = (): ApolloClient<any> => {
  setupServiceApi(API_CONFIG)
  return createServiceApolloClient({ uri: `${API_HOST}${API_PATH}` })
}
Run Code Online (Sandbox Code Playgroud)

getAssetIdFromService.ts

import { setupApi } from '../api/setup'

const client = setupApi()

export const GET_ASSET_ID = gql`
  query getAssetByExternalId($externalId: String!) {
    assetId: getAssetId(externalId: $externalId) {
      id
    }
  }
`

export const getAssetIdFromService = async (externalId: string) => {
  return await client.query({
    query: …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocking jestjs graphql apollo-client

8
推荐指数
1
解决办法
2万
查看次数

标签 统计

apollo-client ×1

graphql ×1

jestjs ×1

mocking ×1

unit-testing ×1