DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Async Context Manager Mocking in Python Tests
  • Building a Tic-Tac-Toe Game Using React
  • Organizing Knowledge With Knowledge Graphs: Industry Trends
  • Best Practices for Building the Data Pipelines

Trending

  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Start Coding With Google Cloud Workstations
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Chaos Engineering for Microservices
  1. DZone
  2. Data Engineering
  3. Databases
  4. Testing GraphQL Server in Node.js

Testing GraphQL Server in Node.js

When we started using GraphQL in our NodeJS project, we struggled with writing tests. So, we made one ourselves. Here, we share our way of testing GraphQL queries.

By 
Nesha Zoric user avatar
Nesha Zoric
·
Apr. 25, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.6K Views

Join the DZone community and get the full member experience.

Join For Free

When we started using GraphQL in our Node.js project, we had a struggle with writing tests. We read numerous blogs, searching for the best way. Unfortunately, there didn't seem to be one, so we made one ourselves. Here, we'll share our way of testing GraphQL queries.

First, we will set up everything needed for running tests:

npm i --save-dev mocha chai supertest graphql 

Now that we have everything installed, we can go ahead and import all the dependencies we will use in our User.test.js file:

const chai = require('chai');

const expect = chai.expect;
const url = `http://localhost:3001/`;
const request = require('supertest')(url);

describe('GraphQL', () => {
    // Tests
});

Setup is even easier than setting up RSpec for testing!

Before running any test, we will have to add a command to our package.json "scripts":

  "scripts": {
      "test": "mocha test/*.test.js"
   }

This will tell Mocha to test all the files with the .test extension in our test folder. To run the test, just type npm test.

It will say 0 passing since we haven't written any test cases yet.

Follow our organizational guidelines for the SailsJS + GraphQL app!

Let's define a GraphQL schema that we will use to write tests. For instance, here, we'll create a User type with some basic information about the user in UserType.js file:

const graphql = require('graphql');

export default new graphql.GraphQLObjectType({
name : 'UserType',
 fields : {
     id : {
         type : graphql.GraphQLInt
     },
     name : {
         type : graphql.GraphQLString
     },
     username:{
         type: graphql.GraphQLString
     },
     email : {
         type : graphql.GraphQLString
     }
});

We're organizing our tests the similar way we organize RSpec controller tests!

Let's define the query field that will return users with the fields we defined just now:

 const graphql = require('graphql');
 const UserType =  require('./UserType').default;

 export default {
  user: {
    description: 'Returns information about user/s',
    type: new graphql.GraphQLList(UserType),
    args: {
      id: { type: graphql.GraphQLInt },
    },
    resolve: async (_, { id }) => {
        if (id) return User.find({ id })
        return User.find() 
    }
  },

For us to be able to query users, we will have to define GraphQL schema:

 const graphql = require('graphql');
 const UserQuery = require('./UserQuery');
 
 export default new graphql.GraphQLSchema({
     name: 'Query',
     fields: UserQuery
 })

The last thing to do before we start writing the tests is to create a universal GraphQL controller that will be triggered for every query, so our client app (we're using React) has an endpoint to make requests to, and our tests, too.

const graphql = require('graphql');
const schema = require('./schema').default;

module.exports = {
  graphql: async (req, res) => {
    try {
      const result = await graphql(schema, req.body.query, req);
      if (result.errors) throw (result.errors);
      return res.ok(result);
    } catch (err) {
      return res.badRequest(err);
    }
  },

Now that we have defined our User type, defined the query object for it, and included it in our GraphQLSchema, we're all set to write tests.

Let's assume that there are some users in our database, the only thing left is to send requests with supertest to our GraphQLController and to output the results of our query:

const chai = require('chai');

const expect = chai.expect;
const url = `http://localhost:3001/`;
const request = require('supertest')(url);

describe('GraphQL', () => {
    it('Returns user with id = 10', (done) => {
        request.post('/graphql')
        .send({ query: '{ user(id: 10) { id name username email } }'})
        .expect(200)
        .end((err,res) => {
            // res will contain array with one user
            if (err) return done(err);
            res.body.user.should.have.property('id')
            res.body.user.should.have.property('name')
            res.body.user.should.have.property('username')
            res.body.user.should.have.property('email')
            done();
        })
    })

    it('Returns all users', (done) => {
        request.post('/graphql')
        .send({ query: '{ user { id name username email } }' })
        .expect(200)
        .end((err, res) => {
            // res will contain array of all users
            if (err) return done(err);
            // assume there are a 100 users in the database
            res.body.user.should.have.lengthOf(100);
        })  
    })
});

Of course, the chai library provides much more options to check out.

With this, we come to the end of this article.

Hope you enjoyed it and found it informative!

GraphQL Database Testing Node.js

Published at DZone with permission of Nesha Zoric, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Async Context Manager Mocking in Python Tests
  • Building a Tic-Tac-Toe Game Using React
  • Organizing Knowledge With Knowledge Graphs: Industry Trends
  • Best Practices for Building the Data Pipelines

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!