ash007
ash007

Reputation: 333

How to mock a database object in GraphQL resolver using Sinon?

I want to be able to unit test my apollo resolvers. The application I am building is a multitenant app which connects to the specific database at the run time i.e the database is not known at the build time.

The resolver looks like this

getTemplates: async (_, args, { db }) => {
  const result = await db.goalTemplate.findAll()
  return result.slice(0, args.first)
},

Though this is the simplest resolver, it gets the db connection object in context parameter that it receives from apollo gateway (I am using apollo federation).

I want to mock this db object so that I can unit test this resolver using sinon.js. Is it even a good idea to unit test these resolvers? If yes, how should I write the test case that I can replicate in other similar but more complex resolvers.

Upvotes: 0

Views: 948

Answers (1)

Lin Du
Lin Du

Reputation: 102327

Use sinon.stub() to create stub for db.goalTemplate.findAll() method.

E.g.

resolver.ts:

export const resolvers = {
  getTemplates: async (_, args, { db }) => {
    const result = await db.goalTemplate.findAll();
    return result.slice(0, args.first);
  },
};

resolver.test.ts:

import { resolvers } from './resolver';
import sinon from 'sinon';
import { expect } from 'chai';

describe('65888128', () => {
  it('should pass', async () => {
    const mDb = {
      goalTemplate: {
        findAll: sinon.stub().resolves([1, 2, 3]),
      },
    };
    const actual = await resolvers.getTemplates({}, { first: 2 }, { db: mDb });
    expect(actual).to.be.eql([1, 2]);
    sinon.assert.calledOnce(mDb.goalTemplate.findAll);
  });
});

unit test result:

  65888128
    ✓ should pass


  1 passing (5ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |                   
 resolver.ts |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------

Upvotes: 4

Related Questions