Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using with Next and ApolloClient #46

Open
dabaquita opened this issue Mar 25, 2022 · 0 comments
Open

Using with Next and ApolloClient #46

dabaquita opened this issue Mar 25, 2022 · 0 comments

Comments

@dabaquita
Copy link

dabaquita commented Mar 25, 2022

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: "[email protected]",
        password: "password"
      }
    });

    expect(userResult).toMatchInlineSnapshot(`
Object {
  "data": Object {
    "registerUser": Object {
      "__typename": "UserLoginPayload",
      "user": Object {
        "__typename": "User",
        "email": "[email protected]",
        "firstName": "FirstName",
      },
    },
  },
}
`);
  });

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

    expect(persistedData).toMatchInlineSnapshot(`Array []`);
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant