Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何用笑话模拟pg promise库_Unit Testing_Promise_Pg Promise - Fatal编程技术网

Unit testing 如何用笑话模拟pg promise库

Unit testing 如何用笑话模拟pg promise库,unit-testing,promise,pg-promise,Unit Testing,Promise,Pg Promise,我试图嘲笑pg promise库。我希望无论承诺是否被拒绝或解决,我都能得到回报。下面是一个函数和测试示例: const pgp = require('pg-promise')({}); const someFunc = callback => { const db = pgp('connectionString'); db .none('create database test;') .then(() => { callback(null, '

我试图嘲笑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);
    });
  });
});

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

您可以看看我最近发布的一个库,它模拟了内存中的postgres实例

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

我写了一篇关于它的文章


对于您的用例,请参见

您测试它的方法与测试任何promise库的方法相同。如果你不知道怎么做,那就四处看看。示例:当然,如果您只想测试快乐之路,那么这是可行的。假设我需要确保在数据库层发生错误时的正确行为,但是,在这种情况下,这没有帮助。