我正在尝试模拟pg promise库。我希望无论承诺拒绝还是解决都能够模拟返回。这是一个示例函数和测试:

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
};


我想这样测试:

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);
    });
  });
});

最佳答案

您可以使用哑模拟来模拟pgp对象,如下所示:

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);
    });
  });
});

关于unit-testing - 如何用玩笑 mock pg-promise库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47456900/

10-09 14:47