Skip to content

How to test with custom ApolloClientOptions? #1880

Open
@Butterbluemchen

Description

@Butterbluemchen

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions