首页 > 解决方案 > 用 Jest 模拟 ApolloClient 的 client.query 方法

问题描述

2020 年 1 月 22 日更新

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

TypeError:无法读取未定义的属性“查询”

好吧,事实证明这是我resetMocks: true设置的笑话配置。在我删除它之后,测试确实通过了。(虽然我不知道为什么)


原始问题:

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

安装程序.ts

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

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: GET_ASSET_ID,
    variables: { externalId },
  })

  return { data, errors, loading }
}

现在我正在尝试为该getAssetIdFromService函数编写测试测试,但我无法弄清楚如何让该client.query方法在测试中工作。

我尝试了以下方法,包括许多其他不起作用的方法。对于这个特定的设置,开玩笑抛出

TypeError:client.query 不是函数

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

jest.mock('../../api/setup', () => ({
  setupApi: () => jest.fn(),
}))

describe('getAssetIdFromService', () => {
  it('returns an assetId when passed an externalId and the asset exists in the service', async () => {
    const { data, errors, loading } = await getAssetIdFromService('e1')

    // Do assertions  
  })
}

我想我错过了与这部分有关的一些东西:

jest.mock('../../api/setup', () => ({
  setupApi: () => jest.fn(),
}))

......但我看不到它。

标签: unit-testingmockinggraphqljestjsapollo-client

解决方案


你没有正确模拟。这是正确的方法:

getAssetIdFromService.ts

import { setupApi } from './setup';
import { gql } from 'apollo-server';

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: GET_ASSET_ID,
    variables: { externalId },
  });
};

setup.ts

export const setupApi = (): any => {};

getAssetIdFromService.test.ts

import { getAssetIdFromService, GET_ASSET_ID } from './getAssetIdFromService';
import { setupApi } from './setup';

jest.mock('./setup.ts', () => {
  const mApolloClient = { query: jest.fn() };
  return { setupApi: jest.fn(() => mApolloClient) };
});

describe('59829676', () => {
  it('should query and return data', async () => {
    const client = setupApi();
    const mGraphQLResponse = { data: {}, loading: false, errors: [] };
    client.query.mockResolvedValueOnce(mGraphQLResponse);
    const { data, loading, errors } = await getAssetIdFromService('e1');
    expect(client.query).toBeCalledWith({ query: GET_ASSET_ID, variables: { externalId: 'e1' } });
    expect(data).toEqual({});
    expect(loading).toBeFalsy();
    expect(errors).toEqual([]);
  });
});

覆盖率 100% 的单元测试结果:

 PASS   apollo-graphql-tutorial  src/stackoverflow/59829676/getAssetIdFromService.test.ts (8.161s)
  59829676
    ✓ should query and return data (7ms)

--------------------------|----------|----------|----------|----------|-------------------|
File                      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------------|----------|----------|----------|----------|-------------------|
All files                 |      100 |      100 |      100 |      100 |                   |
 getAssetIdFromService.ts |      100 |      100 |      100 |      100 |                   |
--------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.479s

源代码:https ://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/59829676


推荐阅读