samedi 24 novembre 2018

NodeJS dependency injection for testing leveldb with require-inject

I have a simple wrapper module I'm using to access Level DB.

I'm trying to write some test using mocha, chai, sinon and require-inject What I would like to test it that the LevelDB functions are called with the correct parameters. I have tried a number of different combinations for setting up require-inject, however, the mock/spies I pass in seem to cause the tests to crash. Does anyone know what I'm doing wrong?

Test Code

const expect = require('chai').expect;
const sinon = require('sinon');
const requireInject = require('require-inject');

let putSpy = sinon.spy();
let getSpy = sinon.spy();

const starDB = requireInject('./star_db', {
  'level' : () => ({
      put: sinon.stub().resolves(putSpy),
      get: sinon.stub().resolves(getSpy)
    })
});

describe('star db', () => {

  afterEach(() => {
    putSpy.resetHistory();
    getSpy.resetHistory();
  });

  it('Given add called then the put method on the db should be called', () => {
    const key = 1;
    const value = 2;

    starDB.add(key, value);
    console.log('putSpy');

    expect(putSpy.calledWith(key, value)).to.be.true;
  });

  it.skip('given a key does not exist in the db then it should return an empty object', async () => {
    const result = await starDB.get('KeyDoesNotExist');

    expect(result).to.deep.equal({});
  });
});

LevelDB wrapper code

const level = require('level');
const dbName = './.verification_data';
const db = level(dbName);

const add = async (key, value) => {
  await db.put(key, JSON.stringify(value));
};

const get = async (key) => {
  let value = await db.get(key)
    .then(result => {
      return JSON.parse(result);
    })
    .catch(error => {
      console.log('unhandledRejection', error);
      return {};
    });

  return value;
};

module.exports = {
  add,
  get
}

Aucun commentaire:

Enregistrer un commentaire