我有一个用于访问Level DB的简单包装器模块。
我正在尝试使用mocha,chai,sinon和require-inject编写一些测试 我想测试一下是否使用正确的参数调用了LevelDB函数。我尝试了多种不同的组合来设置require-inject,但是,我通过的模拟/间谍似乎导致测试崩溃。有人知道我在做什么错吗?
测试代码
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包装器代码
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
}
我当前遇到的错误是
unhandledRejection SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse (<anonymous>)
at db.get.then.result (./db_wrapper.js:12:19)
at <anonymous>