How to mock mongodb for unit testing graphql resolver

Viewed 855

I am learning graphql and want to do the unit testing for my resolver ( i.e. the query to get "answers").The problem is my resolver use mongoose to query data from mongodb behind the scene and I dont know how to mock these calls.

Could anyone help me with this ? Thank you.

The resolver for my query is sth like this:

const { Book, Author } = require('../models')    

module.exports = {
  answers: async ( parent, { searchText } ) => {        
    let authors = null;
    let books = null;
    try {
        authors = await Author.find({});            
        books = await Book.find({}); 
        return getAnswers(authors,books, searchText);
    }catch (err) {
        console.log(err);
    }        
    return null;
 }
}

function getAnswers(books,authors,text) {
    <!-- process data here -->
}
2 Answers

You are looking for proxyquire. It lets you override the dependencies in a file you require. Your test file could look something like this

const proxyquire = require('proxyquire');
const mockBook = {...}

describe('Test #1', function() {
    const stubs = {
        '../models': {
            Book: {
                find: () => Promise.resolve(mockBook),
            },
            Author: // Same as book
        },
    };

    const myfile = proxyquire('./myfile', stubs);
    let answers;

    before(async function() {
        answers = await myfile.answers();
    });

    describe("should succeed", function() {
        expect(answers).to.be.equal(ExpectedAnswers);
    });
});

Now, that code has not been run and will definitely not succeed. This was to give you an idea of how to use proxyquire.

As for the getAnswers() part of the code, you will need to mock the dependencies of that function as well, like it is done for Book in the sample above.

You can use graphql-tools here is a link to the blog

npm install graphql-tools

import your schema into your test file

import { mockServer } from 'graphql-tools';
import schema from './schema.js';

describe('mock server', () => {
  it('should mock the server call', async () => {
    const myMockServer = mockServer(schema, {
      String: () => 'Hello', // <--- expecting a `hello` to be returned
    });
    const response = await myMockServer.query(`{
      users {
        username,
      }
    }`);

    const expected =  { // This shape of the data returned
      data: {
        users: [
          {
            "username": "Hello"
          },
          {
            "username": "Hello"
          },
       ]
    }
  }
  expect(response).toMatchObject(expected);
});
});
Related