如何使用sinon保持oracledb?

时间:2018-05-04 18:12:36

标签: node.js sinon stub

这是我的函数,它将从oracle数据库获取数据后返回一个promise:

const getDataFromOracleDB = (filter, query) =>
  new Promise(async (resolve, reject) => {
    let conn;
    try {
      conn = await oracledb.getConnection(dbConfig);
      const result = await conn.execute(query, [filter]);
      const { rows } = result;
      ...
    catch (err) {
      ...
    }
  };    

作为单元测试,我想要存根conn.execute,但不知道如何做到这一点。我很沮丧:

const stub = sinon.stub(conn, 'execute').returns([1, 2, 3]);

但得到了:

TypeError: Cannot stub non-existent own property execute

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我无法使用您提供的代码复制错误,但也许这个快速模型会有所帮助:

const chai = require('chai');
const sinon = require('sinon');
const oracledb = require('oracledb');
const config = require('./dbConfig.js');

const expect = chai.expect;

sinon.stub(oracledb, 'getConnection').resolves({
  execute: function() {},
  close: function() {}
});

describe('Parent', () => {
  describe('child', () => {
    it('should work', async (done) => {
      let conn;

      try {
        conn = await oracledb.getConnection(config);

        sinon.stub(conn, 'execute').resolves({
          rows: [[2]]
        });

        let result = await conn.execute(
          'select 1 from dual'
        );

        expect(result.rows[0][0]).to.equal(2);

        done();
      } catch (err) {
        done(err);
      } finally {
        if (conn) {
          try {
            await conn.close();
          } catch (err) {
            console.error(err);
          }
        }
      }
    });
  });
});

查询通常会返回值1,但这会返回2并传递。