How to mock pg-promise library with jest

Viewed 2531

I am trying to mock the pg promise library. I want to be able mock return whether the promise rejects or resolves. Here is an example function and test:

const pgp = require('pg-promise')({});

const someFunc = callback => {
  const db = pgp('connectionString');
  db
    .none('create database test;')
    .then(() => {
      callback(null, 'success');
    })
    .catch(err => {
      callback(err);
    });
};

module.exports = {
  someFunc
};

And i wanna test it like so:

const { someFunc } = require('./temp');
let pgp = require('pg-promise')({
  noLocking: true
});
// HOW TO MOCK?

describe('test', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
  });
  it('should test', () => {
    let db = pgp('connectionString');
    // how to mock this?

    db.none = jest.fn();
    db.none.mockReturnValue(Promise.reject('mock'));
    const callback = jest.fn();
    someFunc(callback);
    return new Promise(resolve => setImmediate(resolve)).then(() => {
      expect(callback.mock.calls.length).toEqual(1);
    });
  });
});
2 Answers

You can mock the pgp object with a dumb mock like so:

const { someFunc } = require('./temp');
let pgp = jest.fn(() => ({
  none: jest.fn(),
})

jest.mock('pg-promise')  // Jest will hoist this line to the top of the file
                         // and prevent you from accidentially calling the
                         // real package.

describe('test', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
  });

  it('should test', () => {
    let db = pgp('connectionString');
    db.none.mockRejectedValue('mock');  // This is the mock
    const callback = jest.fn();
    someFunc(callback);
    return new Promise(resolve => setImmediate(resolve)).then(() => {
      expect(callback.mock.calls.length).toEqual(1);
    });
  });
});

Its an old question, but here is a new answer:

You can have a look at pg-mem, a library I released recently which emulates an in-memory postgres instance.

It supports most of the usual SQL queries (but will fail on less frequent syntaxes - file an issue if you encounter such a situation).

I wrote an article about it here

For your use case, see the this section

Related