模拟ES6 BigQuery类

圆环面

我有一个包装基本的大查询操作的小类:

const { BigQuery } = require('@google-cloud/bigquery');


export default class BQ {
    bigquery;

    constructor(projectId, keyFilename) {
        const options = {
            projectId,
            keyFilename,
            autoRetry: true,
        };
        
        this.bigquery = new BigQuery(options);
    }

    async query(query) {
        const options = {
            query,
            location: 'us',
        };
        const [job] = await this.bigquery.createQueryJob(options);
        const [rows] = await job.getQueryResults();
        return rows;
    }
}

我正在尝试为该query方法编写摩卡单元测试但是,我一直坚持在js中创建模拟程序。Sinon,沙箱,存根等有很多选项。我认为我需要对实例属性进行存根,例如,

const bq = new BQ(projectId, keyFilename);
const bqStub = sandbox.stub(bq, 'bigquery');

但是也有一些方法一直试图对Google进行实际身份验证,我也需要将其存根。关于如何开始的任何帮助都将是很棒的。

幻灯片放映

您可以将Link Seams与CommonJS一起使用,我们需要proxyquire来构造我们的接缝。

例如

bq.js

const { BigQuery } = require('@google-cloud/bigquery');

export default class BQ {
  bigquery;

  constructor(projectId, keyFilename) {
    const options = {
      projectId,
      keyFilename,
      autoRetry: true,
    };

    this.bigquery = new BigQuery(options);
  }

  async query(query) {
    const options = {
      query,
      location: 'us',
    };
    const [job] = await this.bigquery.createQueryJob(options);
    const [rows] = await job.getQueryResults();
    return rows;
  }
}

bq.test.js

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

describe('62492844', () => {
  it('should pass', async () => {
    const rows = [{ id: 1 }, { id: 2 }];
    const job = {
      getQueryResults: sinon.stub().returns([rows]),
    };
    const bigquery = {
      createQueryJob: sinon.stub().returns([job]),
    };
    const BigQueryStub = sinon.stub().returns(bigquery);
    const BQ = proxyquire('./bq', {
      '@google-cloud/bigquery': { BigQuery: BigQueryStub },
    }).default;

    const bq = new BQ('projectId', './svc.json');
    sinon.assert.calledWithExactly(BigQueryStub, {
      projectId: 'projectId',
      keyFilename: './svc.json',
      autoRetry: true,
    });
    const actual = await bq.query('query');
    sinon.assert.calledWithExactly(bigquery.createQueryJob, { query: 'query', location: 'us' });
    sinon.assert.calledOnce(job.getQueryResults);
    sinon.assert.match(actual, rows);
  });
});

单元测试结果:

  62492844
    ✓ should pass (2427ms)


  1 passing (2s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 bq.ts    |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章