如何用SINON模拟PG Pool

2022-06-17 00:00:00 node.js javascript sinon pg

在上一个项目中,我用Sinon模拟了mysql library。我是这样做的:

X.js

const con = mysql.createPool(config.mysql);
...

Some other place in the project

const rows = await con.query(query, inserts);
...

X.test.js

const sinon = require('sinon');
const mockMysql = sinon.mock(require('mysql'));
...

mockMysql.expects('createPool').returns({
        query: () => {
            // Handles the query...
        },
...

它工作得很好。

在另一个项目中,我试图模拟pg,同样是用sinon。

pool.js

const { Pool } = require('pg');
const config = require('@blabla/config');
const pool = new Pool(config.get('database'));

module.exports = pool;

Some other place in the project

const con = await pool.connect();
const result = await con.query(...

Y.test.js

???

我不懂如何模仿connect().query()。以下方法均不起作用:

1:

const { Pool } = require('pg');
const config = require('@blabla/config');

const mockPool = sinon.mock(new Pool(config.get('database')));
...
mockPool.expects('connect').returns({
  query: () => {
    console.log('query here');
  },
});

1不会导致错误,但使用的是真实的数据库连接。

2:

const { Pool } = sinon.mock(require('pg'));
const config = require('@blabla/config');

const pool = new Pool(config.get('database'));

pool.expects('connect').returns({
  query: () => {
    console.log('query here');
  },
}); 

2=>TypeError: Pool is not a constructor

3:

const { Pool } = sinon.mock(require('pg'));
const config = require('@blabla/config');

const pool = sinon.createStubInstance(Pool);
pool.connect.returns({
  query: () => {
    console.log('query here');
  },
});

3=>TypeError: The constructor should be a function.

有人能就如何模拟我的PostgreSQL连接给我指个正确的方向吗?


解决方案

示例:我有这样的postgres.js。

const { Pool } = require('pg');

const handler = {
  count: async (pgQuery) => {
    try {
      const pool = new Pool();
      const res = await pool.query(pgQuery);
      return { count: parseInt(res.rows[0].counter, 10) };
    } catch (error) {
      // Log/Throw error here.
    }
    return false;
  }
}

module.exports = handler;

我在postgres.spec.js上创建的规范测试如下所示。

const { expect } = require('chai');
const sinon = require('sinon');
const pgPool = require('pg-pool');
const handler = require('postgres.js');

describe('Postgres', function () {
  it('should have method count that bla bla', async function () {
    // Create stub pgPool query.
    const postgreeStubQuery = sinon.stub(pgPool.prototype, 'query');
    postgreeStubQuery.onFirstCall().throws('XXX');
    postgreeStubQuery.onSecondCall().resolves({
      rows: [{ counter: 11 }],
    });

    // Catch case.
    const catcher = await handler.count('SELECT COUNT()..');
    expect(catcher).to.equal(false);
    expect(postgreeStubQuery.calledOnce).to.equal(true);

    // Correct case.
    const correct = await handler.count('SELECT COUNT()..');
    expect(correct).to.deep.equal({ count: 11 });
    expect(postgreeStubQuery.calledTwice).to.equal(true);

    // Restore stub.
    postgreeStubQuery.restore();
  });
});

若要存根pool.Query(),您需要存根pg-pool原型和方法查询。

希望这能有所帮助。

相关文章