I am looking to find a way to a test graphql server with graphql-request library

271 Views Asked by At

I am using graphql-tag and supertest-graphql to test my apollo-server-express app.

The following is my current approach.

 it('Query a quote', async () => {
    const id = '123456';
    const res = await request(app)
      .query(
        gql`
          query ($id: String!) {
            word(id: $id) {
              id
            }
            words {
              id
            }
          }
        `
      )
      .variables({ id: id });
    console.log(res.data);
    expect((res.data as any).word.id).toBe('123456');
  });

In the client side, I am using graphql-request. This is why I want to use graphql-request's request instead of supertest-graphql's request in my unit tests.

However, I cannot find any solution to do this job. Anyone has any idea?

1

There are 1 best solutions below

0
Nimo shr On

At the end, I started an actual express server to run my test.

something like this:

const app = express();
const port = 3000;
const server = app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`);
});
server.on('error', console.error);

    describe('Quote resolver test', () => {
      beforeAll(async () => {
        const apolloServer = await createApolloServer();
        await apolloServer.start();
        apolloServer.applyMiddleware({ app });
      });
      afterAll(async () => {
        server.close();
      });


      it('Query a quote', async () => {
        const id = '123456';
        const res = await request(
          'http://localhost:3000/graphql/',
          gql`
            query ($id: String!) {
              word(id: $id) {
                id
              }
              words {
                id
              }
            }
          `,
          { id: id }
        );
        console.log((res as any).word);
        expect((res as any).word.id).toBe('123456');
      });

If anyone has a better idea, I am eager to learn.