【问题标题】:How to mock pg-promise library with jest如何用 jest 模拟 pg-promise 库
【发布时间】:2018-05-07 12:03:18
【问题描述】:

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

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

【问题讨论】:

  • 您测试它的方式与测试任何 Promise 库的方式相同。环顾四周,如果你不知道怎么做。示例:coderwall.com/p/axugwa/…
  • 当然,如果您只想测试快乐的路径,那可以。假设我需要确保在数据库层出现错误的情况下行为正确,但在这种情况下这无济于事。

标签: unit-testing promise pg-promise


【解决方案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);
    });
  });
});

【讨论】:

    【解决方案2】:

    这是一个老问题,但这里有一个新答案:

    您可以查看pg-mem,这是我最近发布的一个模拟内存中 postgres 实例的库。

    它支持大多数常见的 SQL 查询(但在不太常见的语法上会失败 - 如果遇到这种情况,请提出问题)。

    我写了一篇关于它的文章here

    对于您的用例,请参阅this section

    【讨论】:

      猜你喜欢
      • 2019-10-10
      • 2021-09-11
      • 2019-12-14
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2018-12-25
      相关资源
      最近更新 更多