kamilkisiela / apollo-angular

A fully-featured, production ready caching GraphQL client for Angular and every GraphQL server 🎁
https://apollo-angular.com
MIT License
1.5k stars 309 forks source link

How to test with custom ApolloClientOptions? #1880

Open Butterbluemchen opened 1 year ago

Butterbluemchen commented 1 year ago

I'm trying to write a test using the ApolloTestingModule and ApolloClientOptions.

I provide custom ApolloClientOptions with the APOLLO_OPTION injection token. In the options I set the "no-cache" fetch-policy for my queries.

In my Test I import the ApolloTestingModule. When I run my test, I get the following error: "Error: Apollo has been already created." I'm not sure which part already created the default client but the ApolloTestingModule also tries to create the default client with the fake backend and a cache (that might be provided).

I made a local copy of the ApolloTestingModuleCore and modified the code a bit:

export class ApolloTestingModuleCore {
  constructor(
    apollo: Apollo,
    backend: ApolloTestingBackend,
    @Optional()
    @Inject(APOLLO_TESTING_CLIENTS)
    namedClients?: string[],
    @Optional()
    @Inject(APOLLO_TESTING_CACHE)
    cache?: ApolloCache<any>,
    @Optional()
    @Inject(APOLLO_TESTING_NAMED_CACHE)
    namedCaches?: any, // FIX: using NamedCaches here makes ngc fail
    @Optional()
    @Inject(APOLLO_OPTIONS)
      options?: ApolloClientOptions<any>,
  ) {
    function createOptions(name: string, c?: ApolloCache<any> | null) {
      return {
        ...options,
        link: new ApolloLink((operation) =>
          backend.handle(addClient(name, operation)),
        ),
        cache:
          c ||
          new InMemoryCache({
            addTypename: false,
          }),
      };
    }

    apollo.removeClient('default');
    apollo.create(createOptions('default', cache));

    if (namedClients && namedClients.length) {
      namedClients.forEach((name) => {
        const caches =
          namedCaches && typeof namedCaches === 'object' ? namedCaches : {};

        apollo.createNamed(name, createOptions(name, caches[name]));
      });
    }
  }
}

When I use the modified version of the ApolloTestingModuleCore everything works as expected.

Is it possible to change this part or is there an intended way to test with ApolloClientOptions?

PowerKiKi commented 1 week ago

I assume you are providing Apollo somewhere else, where you shouldn't.

Can you please provide a Minimal, Complete, and Verifiable example of code that exhibits the issue ?