【问题标题】:How can I trigger a GraphQL error to test an ErrorLink on Apollo Client?如何触发 GraphQL 错误以在 Apollo 客户端上测试 ErrorLink?
【发布时间】:2021-10-08 07:05:35
【问题描述】:

我为 Apollo 客户端设置了以下 ErrorLink。

export const errorLink = onError(
  ({ response, graphQLErrors, networkError, operation }: ErrorResponse) => {
    notificationService.notify("An Error Occurred");
  },
);

我需要在单元测试中测试这个实现。 我有以下测试 Apollo Links

const MockQuery = gql`
  query {
    foo
  }
`;

interface LinkResult<T> {
  operation: Operation;
  result: FetchResult<T>;
}

async function executeLink<T = ApolloLink>(
  linkToTest: ApolloLink,
  request: GraphQLRequest = { query: MockQuery },
) {
  const linkResult = {} as LinkResult<T>;

  return new Promise<LinkResult<T>>((resolve, reject) => {
    execute(ApolloLink.from([linkToTest]), request).subscribe(
      (result) => {
        linkResult.result = result as FetchResult<T>;
      },
      (error) => {
        reject(error);
      },
      () => {
        resolve(linkResult);
      },
    );
  });
}

it('triggers a notification on error', () => {
  const testLink = new ApolloLink(() => {
    await waitFor(() => expect(notificationSpy).toBeCalledWith('An Error Occurred'))

    return null;
  });

  const link = ApolloLink.from([errorLink, testLink]);
  executeLink(link);
});

这些单元测试适用于其他链接,如 AuthLink,我在其中测试身份验证令牌是否设置为 localStorage。但是我无法测试错误链接,因为我无法触发 GraphQL 错误。

【问题讨论】:

    标签: reactjs unit-testing graphql apollo apollo-client


    【解决方案1】:

    您可以create a mocked terminating link并提供GraphQL运算结果。

    例如

    errorLink.ts:

    import { onError } from '@apollo/client/link/error';
    
    type ErrorResponse = any;
    
    export const errorLink = onError(({ response, graphQLErrors, networkError, operation }: ErrorResponse) => {
      console.log('An Error Occurred');
      console.log('graphQLErrors: ', graphQLErrors);
    });
    

    errorLink.test.ts:

    import { ApolloLink, execute, Observable } from '@apollo/client';
    import { gql } from 'apollo-server-express';
    import { errorLink } from './errorLink';
    
    const MockQuery = gql`
      query {
        foo
      }
    `;
    
    describe('68629868', () => {
      test('should pass', (done) => {
        expect.assertions(1);
        const mockLink = new ApolloLink((operation) =>
          Observable.of({
            errors: [
              {
                message: 'resolver blew up',
              },
            ],
          } as any),
        );
    
        const link = errorLink.concat(mockLink);
        execute(link, { query: MockQuery }).subscribe((result) => {
          expect(result.errors![0].message).toBe('resolver blew up');
          done();
        });
      });
    });
    

    测试结果:

     PASS   apollo-graphql-tutorial  src/stackoverflow/68629868/errorLink.test.ts (5.02s)
      68629868
        ✓ should pass (14ms)
    
      console.log src/stackoverflow/68629868/errorLink.ts:6
        An Error Occurred
    
      console.log src/stackoverflow/68629868/errorLink.ts:7
        graphQLErrors:  [ { message: 'resolver blew up' } ]
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        5.067s
    

    包版本:@apollo/client@3.3.20

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2021-10-12
      • 2019-06-12
      • 2021-10-06
      • 2019-02-24
      • 2020-11-24
      • 2019-06-22
      • 2021-11-11
      • 2019-11-02
      相关资源
      最近更新 更多