node-postgres客户端的Sinon存根

问题描述 投票:0回答:1

我正在用TypeScript编写一个Node应用程序,该应用程序正在查询Postgres数据库。在单元测试中,我无法模拟查询功能。

我的单位代码如下:

class MyClass {

  /* more stuff */

  async validate(event: any): Promise<boolean> {
    const client = new Client();
    await client.connect();

    const result = await client.query(`SELECT * FROM "user" WHERE "user_id" = '${user_id}'`);

    console.log(
      result
    );

    /* more logic */
  }
}

我的单元测试看起来像这样:

describe("...", () => {
  sinon.stub(pg.Client.prototype, "connect").resolves();
  let stub = sinon.stub(pg.Client.prototype, "query").withArgs(
    `SELECT * FROM "user" WHERE "user_id" = '1234'`,
     sinon.match.any,
     sinon.match.any
  ).resolves("asdf");

  it("...", () => {
    await myClassInstance.validate(event);
  });
});

[暂时不谈论测试期望,我期望的是控制台上印有“ asdf”。但是我没有!

我已经尝试完全删除.withArgs(...),然后可以看到“ asdf”。 (但是显然,它并没有太大帮助...)

我也尝试过打印stub.lastCall,我知道

args: [ `SELECT * FROM "user" WHERE "user_id" = 'user_with_verified_subscription'` ]

然后在某处...

删除两个sinon.match.any匹配器也无济于事,因为然后TS编译器抱怨Client.query接受3个参数...

非常感谢您的帮助!

最诚挚的问候,

最大

node.js typescript sinon stub node-postgres
1个回答
0
投票

这里是使用proxyquiresinon的单元测试解决方案:

index.ts

import { Client } from 'pg';

class MyClass {
  async validate(event: any) {
    const user_id = 1;
    const client = new Client();
    await client.connect();

    const result = await client.query(`SELECT * FROM "user" WHERE "user_id" = '${user_id}'`);

    console.log(result);
  }
}

export default MyClass;

index.test.ts

import sinon from 'sinon';
import proxyquire from 'proxyquire';

describe('60172091', () => {
  it('should valdiate', async () => {
    const pgClientStub = {
      connect: sinon.stub().returnsThis(),
      query: sinon
        .stub()
        .withArgs(`SELECT * FROM "user" WHERE "user_id" = '1'`)
        .resolves('asdf'),
    };
    const pgStub = sinon.stub().callsFake(() => pgClientStub);
    const MyClass = proxyquire('./index', {
      pg: { Client: pgStub },
    }).default;
    const logSpy = sinon.spy(console, 'log');
    const instance = new MyClass();
    await instance.validate();
    sinon.assert.calledOnce(pgStub);
    sinon.assert.calledOnce(pgClientStub.connect);
    sinon.assert.calledWithExactly(pgClientStub.query, `SELECT * FROM "user" WHERE "user_id" = '1'`);
    sinon.assert.calledWithExactly(logSpy, 'asdf');
  });
});

单元测试结果覆盖率100%:

60172091
asdf
    ✓ should valdiate (2212ms)


  1 passing (2s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
© www.soinside.com 2019 - 2024. All rights reserved.