5

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);
    });
  });
});
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
John Smith
  • 103
  • 1
  • 4
  • You test it the same way one tests any promise library. Look around for those, if you do not know how. Example: https://coderwall.com/p/axugwa/cleaning-the-database-in-between-mocha-tests-with-pg-promise – vitaly-t Nov 23 '17 at 20:13
  • Sure, that works if you only want to test the happy path. Suppose I need to ensure correct behavior in case of an error from the database layer, though - this doesn't help in that circumstance. – Aaron Miller Jun 07 '19 at 14:03

2 Answers2

1

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);
    });
  });
});
tenfishsticks
  • 452
  • 5
  • 13
0

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

Olivier
  • 5,578
  • 2
  • 31
  • 46