首页 > 解决方案 > 不变违规:为了初始化 Apollo 客户端,您必须在单元测试用例的选项对象中指定“链接”和“缓存”属性

问题描述

我有以下 a.jsx 文件,它从中返回 apollo 客户端对象:

import { createAppSyncLink } from "aws-appsync";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { appSyncConfig } from "./client/AwsConfig";
import { fragmentMatcher } from "./client/apollo-cache";

// AppSync link
const awsAppSyncLink = createAppSyncLink({
    url: appSyncConfig.graphqlEndpoint,
    region: appSyncConfig.region,
    auth: {
        type: appSyncConfig.authenticationType,
        apiKey: appSyncConfig.apiKey
    }
});

const links = [awsAppSyncLink];

const apolloLink = ApolloLink.from(links);

export default new ApolloClient({
    cache: new InMemoryCache({ fragmentMatcher }),
    link: apolloLink
});

现在,我正在尝试使用 jest 为该文件运行测试,如下所示:

import { createAppSyncLink } from "aws-appsync";
import { ApolloLink } from "apollo-link";

jest.mock("aws-appsync");
jest.mock("apollo-link");

describe("GraphQL client", () => {

    it("should create a client", () => {
        const client = require("../src/a").default;

        console.log(client);

        expect(client).toBeDefined();
    });
});

但我收到以下错误:

FAIL tst/a.test.js ● GraphQL 客户端 › 应该创建一个客户端

Invariant Violation: In order to initialize Apollo Client, you must specify 'link' and 'cache' properties in the options object.
These options are part of the upgrade requirements when migrating from Apollo Client 1.x to Apollo Client 2.x.
For more information, please visit: https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup

  26 | const apolloLink = ApolloLink.from(links);
  27 |
> 28 | export default new ApolloClient({
     |                ^
  29 |     cache: new InMemoryCache({ fragmentMatcher }),
  30 |     link: apolloLink
  31 | });

  at new InvariantError (node_modules/ts-invariant/lib/invariant.esm.js:12:28)
  at new ApolloClient (node_modules/apollo-client/bundle.umd.js:2484:92)
  at Object.<anonymous> (src/a.jsx:28:16)
  at Object.<anonymous> (tst/a.test.js:10:24)

我对用 Javascript 进行测试和使用 jest 非常陌生。如果有人可以帮助我为这个文件编写测试用例,那就太好了,你怎么做?

标签: javascriptunit-testingjestjsreact-apollo

解决方案


推荐阅读