NestJS how to get apolloClient from the graphql module to test using `apollo-server-testing`?

1.1k Views Asked by At

Although the title is similar to Access to Apollo server for NestJS GraphQL test, the question itself is old and the answers in that question all address behaviour that no longer seems to exist in nestjs.

I have followed the PR here https://github.com/nestjs/graphql/pull/1104 as well as several other threads in an attempt to get the apolloClient from the testing module to run a test query against it without success.

The prevalent error, supported by the typescript compiler is that it simply does not exist on the GraphQlModule. Where is it? why was it removed? how do I access this critical feature?

TypeError: Cannot read properties of undefined (reading 'executeOperation')

      71 | export function createTestClient(testingModule: TestingModule): apolloServerTesting.ApolloServerTestClient {
      72 |     const apolloServer = getApolloServer(testingModule);
    > 73 |     return apolloServerTesting.createTestClient(apolloServer as any);
         |                                ^
      74 | }

functions created based on the PR:

export function getApolloServer(app: INestApplicationContext): ApolloServerBase {
    try {
        const graphqlModule = app.get(GraphQLModule);
        return (graphqlModule as any).apolloServer;
    } catch (error) {}
    throw new Error(
        'Nest could not find either the GraphQLFederationModule or GraphQLModule. Both modules are not registered in the given application.',
    );
}

export function createTestClient(testingModule: TestingModule): apolloServerTesting.ApolloServerTestClient {
    const apolloServer = getApolloServer(testingModule);
    return apolloServerTesting.createTestClient(apolloServer as any);
}

Versions:

  "@nestjs/apollo": "10.0.6",
  "@nestjs/common": "8.4.0",
  "@nestjs/core": "8.4.0",
  "@nestjs/graphql": "10.0.6",
  "@nestjs/platform-express": "8.4.0",
  "apollo-server-express": "3.6.3",
  "apollo-server-integration-testing": "^3.0.0",
  "apollo-server-testing": "^2.25.3",

Usage in a specific test:

        const result = await apolloClient.query({
            query: gql`.........

The vscode intellisense will let me know if I remove 'as any' that the functions in that PR are not working/accurate:

enter image description here

0

There are 0 best solutions below