【问题标题】:How can i test a TypeORM repository method with local dependency我如何测试具有本地依赖关系的 TypeORM 存储库方法
【发布时间】:2020-04-01 20:21:46
【问题描述】:

我是 Node 新手,我正在尝试使用 Mocha 和 Sinon 测试 TypeORM 自定义存储库,而无需访问数据库。

My 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 方法中实例化的那个。我的问题:

  • 是否可以窥探这样的方法?
  • 此方法是否“可单元测试”?或者我应该只针对某些功能/集成测试进行测试。

提前谢谢你。

【问题讨论】:

  • 这个答案提供了几个选项来实现这一点:stackoverflow.com/a/44482001/200987。如果您想知道如何在某种意义上应用它,请说出来。您可以使用多种手动 DI 技术或 proxyquire。还请查看我们的操作方法:sinonjs.org/how-to
  • 谢谢您,根据您的建议,我现在有一个工作版本的测试!

标签: node.js unit-testing mocha.js sinon typeorm


【解决方案1】:

感谢@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();

    });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多