Skip to content

Using with Next and ApolloClient #46

@dabaquita

Description

@dabaquita

I am trying to follow this tutorial to establish integration tests on our web application. Our stack currently includes Nexus, Next, Apollo, Prisma, and PostgreSQL.

I am using ApolloClient in place of GraphQLClient from graphql-request, I opted to use ApolloClient instead, especially since our web application is server less.

This is currently what I have inside the helper.ts, and the ApolloClient does work when I execute mutations. However, after executing a mutation on ApolloClient and checking if the data persists through Prisma, I get a null value.

Did I do these adjustments correctly? I am definitely missing something if Prisma is not querying correctly. Maybe there is a disconnect here between ApolloClient and Prisma or ApolloClient and the database? Any help would be much appreciated.

All of the code is below.

helper.ts

function graphqlTestContext() {
 let serverInstance: ServerInfo | null = null;

 return {
   async before() {
     const rootUrl = getRootUrl();

     const httpLink = createHttpLink({
       uri: rootUrl + "api/graphql",
       credentials: "include",
       fetch
     });
   
     const client = new ApolloClient({
       // ssrMode: typeof window === "undefined",
       link: httpLink,
       cache: new InMemoryCache(),
     });

     return client;
   },
   async after() {
     serverInstance?.server.close()
   },
 }
}

function prismaTestContext() {
 const prismaBinary = join(__dirname, '../../', 'node_modules', '.bin', 'prisma');
 let schema = '';
 let databaseUrl = '';
 let prismaClient: null | PrismaClient = null;

 return {
   async before() {
     // Generate a unique schema identifier for this test context
     schema = `test_${nanoid()}`;
     // Generate the pg connection string for the test schema
     databaseUrl = `${process.env.ROOT_DB_URL}/testing?schema=${schema}`;

     // Set the required environment variable to contain the connection string
     // to our database test schema
     process.env.DATABASE_URL = databaseUrl;

     // Run the migrations to ensure our schema has the required structure
     execSync(`${prismaBinary} migrate dev`, {
       env: {
         ...process.env,
         DATABASE_URL: databaseUrl,
       },
     });

     // Construct a new Prisma Client connected to the generated Postgres schema
     prismaClient = new PrismaClient();

     return prismaClient;
   },
   async after() {
     // Drop the schema after the tests have completed
     const client = new Client({
       connectionString: databaseUrl,
     });
     await client.connect();
     await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
     await client.end();

     // Release the Prisma Client connection
     await prismaClient?.$disconnect();
   },
 }

User.int.test.ts

const ctx = createTestContext();

describe("User", () => {
  it("creates a new user with REGISTER_MUTATION", async () => {
    const userResult = await ctx.client.mutate({
      mutation: gql`
      mutation Register(
        $firstName: String!
        $lastName: String!
        $email: String!
        $password: String!
      ) {
        registerUser(
          firstName: $firstName
          lastName: $lastName
          email: $email
          password: $password
        ) {
          user {
            email
            firstName
          }
        }
      }
      `, 
      variables: {
        firstName: "FirstName",
        lastName: "LastName",
        email: "test@email.com",
        password: "password"
      }
    });

    expect(userResult).toMatchInlineSnapshot(`
Object {
  "data": Object {
    "registerUser": Object {
      "__typename": "UserLoginPayload",
      "user": Object {
        "__typename": "User",
        "email": "test@email.com",
        "firstName": "FirstName",
      },
    },
  },
}
`);
  });

  it("verifies that user persists", async () => {
    const persistedData = await ctx.prisma.user.findMany();

    expect(persistedData).toMatchInlineSnapshot(`Array []`);
  });
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions