Если вы хотите смоделировать или заглушить какой-нибудь пакет / метод / модуль, вам нужно установить библиотеку макета / заглушки, такую как sinon.js
, jest.js
, чтобы достичь этого.
Вот модульный тест решение с использованием sinon.js
. Для простоты и ясности я удалил ненужные детали, такие как DI.
db.ts
:
import { Pool } from "pg";
export class DbAccess {
private static readonly postgres = new Pool();
public saveConsumer(consumer) {
return DbAccess.postgres.query(`
INSERT INTO users (consumer_id, email)
VALUES (${consumer.consumer_id}, ${consumer.email})
ON CONFLICT (consumer_id) DO UPDATE SET email = ${consumer.email}
RETURNING *
`);
}
}
db.test.ts
:
import pg from "pg";
import sinon from "sinon";
import { expect } from "chai";
describe("59624370", () => {
afterEach(() => {
sinon.restore();
});
it("should pass", async () => {
const mPool = { query: sinon.stub().resolves({ rows: [] }) };
const poolStub = sinon.stub(pg, "Pool").callsFake(() => mPool);
const { DbAccess } = require("./db");
const db = new DbAccess();
const consumer = { consumer_id: 1, email: "example@gmail.com" };
const actual = await db.saveConsumer(consumer);
expect(actual).to.be.eql({ rows: [] });
sinon.assert.calledOnce(poolStub);
sinon.assert.calledOnce(mPool.query);
});
});
Юнит-тест результаты с отчетом о покрытии:
59624370
✓ should pass (132ms)
1 passing (141ms)
------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
db.test.ts | 100 | 100 | 100 | 100 | |
db.ts | 100 | 100 | 100 | 100 | |
------------|----------|----------|----------|----------|-------------------|
Исходный код: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59624370