How to stub oracledb with sinon?

让人想犯罪 __ 提交于 2020-01-06 07:19:14

问题


Here is my function which will return a promise once it gets data from oracle database:

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) {
      ...
    }
  };    

As the unit test, I want to stub conn.execute, but have no idea how to do that. I've treid:

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

But got:

TypeError: Cannot stub non-existent own property execute

Any suggestions?


回答1:


I can't replicate the error with the code you supplied, but perhaps this quick mockup will help:

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);
          }
        }
      }
    });
  });
});

The query would normally return a value of 1, but this returns 2 and passes.



来源:https://stackoverflow.com/questions/50180905/how-to-stub-oracledb-with-sinon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!