簡體   English   中英

我如何測試具有本地依賴性的 TypeORM 存儲庫方法

[英]How can i test a TypeORM repository method with local dependency

我是 Node 的新手,我正在嘗試使用 Mocha 和 Sinon 測試 TypeORM 自定義存儲庫,而不會訪問數據庫。

我的 Repository 有一個方法,它接受 2 個參數並返回一個 Promise。 它使用本地查詢構建器,我想監視它(queryBuilder)以了解其方法被調用的次數。 這是我的自定義存儲庫:


@EntityRepository(Pratica)
export class PraticaRepository extends Repository<Pratica> {

    list(targa?: string, tipoVeicolo?: string): Promise<Pratica[]> {
        fileLogger.log('info','inizio -  targa: %s; tipoVeicolo %s.', targa, tipoVeicolo);

        let queryBuilder: SelectQueryBuilder<Pratica> = this.createQueryBuilder("p")
        .leftJoinAndSelect("p.stato", "stato")
        .leftJoinAndSelect("p.microstato", "microstato");
        let filtered: boolean = false;

        if(targa && targa !== ""){
            fileLogger.debug("Applico filtro targa");
            filtered = true;
            queryBuilder.where("p.targa = :targa", {targa: targa});
        }

        if(tipoVeicolo && tipoVeicolo !== ""){
            if(!filtered){
                fileLogger.debug("Applico filtro tipoVeicolo");
                filtered = true;
                queryBuilder.where("p.tipoVeicolo = :tipoVeicolo", {tipoVeicolo: tipoVeicolo});
            }else{
                fileLogger.debug("Applico filtro tipoVeicolo come parametro aggiuntivo");
                queryBuilder.andWhere("p.tipoVeicolo = :tipoVeicolo", {tipoVeicolo: tipoVeicolo});
            }
        }

        fileLogger.log('debug', "Sql generato: %s", queryBuilder.getSql);
        fileLogger.info("fine");

        return queryBuilder.getMany();

    }

我已經嘗試過類似以下的事情:

describe('PraticaRepository#list', () => {

    it.only('should call getMany once', async () => {

        let result = new Promise((resolve,reject) => {
            resolve(new Array(new Pratica(), new Pratica()))
        });

        let getMany = sinon.stub().returns(result);

        typeorm.createQueryBuilder = sinon.stub().returns({
            select: sinon.stub(),
            from: sinon.stub(),
            leftJoinAndSelect: sinon.stub(),
            where: sinon.stub(),
            orderBy: sinon.stub(),
            getMany: getMany
          })

        let cut = new PraticaRepository();

        const appo = cut.list('','');

        sinon.assert.calledOnce(getMany);
    });
})

但顯然我收到以下錯誤:

1) PraticaRepository#list
       should call getMany once:
     TypeError: Cannot read property 'createQueryBuilder' of undefined
      at PraticaRepository.Repository.createQueryBuilder (src\repository\Repository.ts:50:29)
      at PraticaRepository.list (src\repositories\PraticaRepository.ts:12:62)

因為我存根的查詢構建器不是在 Repository 方法中實例化的那個。 我的問題:

  • 是否可以監視這樣的方法?
  • 這種方法是“單元可測試的”嗎? 或者我應該只針對某些功能/集成測試來測試它。

先感謝您。

感謝@oligofren 的建議,這是我的最終解決方案:

let sandbox;
let createQueryBuilderStub;
let mock;
let fakeQueryBuilder = new SelectQueryBuilder<Pratica>(null);

beforeEach(() => {
    sandbox = sinon.createSandbox();

    mock = sandbox.mock(fakeQueryBuilder);

    createQueryBuilderStub = sandbox.stub(Repository.prototype, 
'createQueryBuilder').withArgs("p").returns(fakeQueryBuilder);
});

afterEach(() => {
    sandbox.restore();
});

describe('PraticaRepository#list', () => {

    it('should get the result with no filters', async () => {

        mock.expects('leftJoinAndSelect').twice().returns(fakeQueryBuilder);
        mock.expects('where').never();
        mock.expects('andWhere').never();
        mock.expects('getSql').once();
        mock.expects('getMany').once();

        let cut = new PraticaRepository();

        const appo = cut.list();

        sinon.assert.calledOnce(createQueryBuilderStub);
        mock.verify();

    });
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM