Skip to content

Commit

Permalink
add support for Sinon-decorated properties
Browse files Browse the repository at this point in the history
  • Loading branch information
frankthelen committed Nov 23, 2018
1 parent 6271819 commit 7b0ebc9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
11 changes: 8 additions & 3 deletions src/SequelizeSimpleCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,21 @@ class SequelizeSimpleCache {
}
}
const promise = target[prop](...args);
assert(promise.then, `${name}.${prop} did not return a promise`);
assert(promise.then, `${name}.${prop}() did not return a promise but should`);
return promise.then((data) => {
if (data !== undefined && data !== null) {
this.cache.set(hash, { data, expires: Date.now() + ttl * 1000, type: name });
}
return Promise.resolve(data); // resolve from database
});
};
fn.restore = () => target[prop].restore(); // TODO: Sinon support
return fn;
return new Proxy(fn, { // support Sinon-decorated properties
get: (_, deco) => { // eslint-disable-line consistent-return
if (Reflect.has(target, prop) && Reflect.has(target[prop], deco)) {
return target[prop][deco]; // e.g., `User.findOne.restore`
}
},
});
},
};
return new Proxy(model, interceptor);
Expand Down
8 changes: 4 additions & 4 deletions test/SequelizeSimpleCache.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ describe('SequelizeSimpleCache', () => {
expect(stubConsoleDebug.called).to.be.false;
});

it('should work to stub models using Sinon in unit tests / restore variant 1', async () => {
it('should work to stub models using Sinon in unit tests / option 1', async () => {
const model = {
name: 'User',
findOne: async () => ({ username: 'fred' }),
Expand All @@ -303,19 +303,19 @@ describe('SequelizeSimpleCache', () => {
stub.restore();
});

it('should work to stub models using Sinon in unit tests / restore variant 2', async () => {
it('should work to stub models using Sinon in unit tests / option 2', async () => {
const model = {
name: 'User',
findOne: async () => ({ username: 'fred' }),
};
const cache = new SequelizeSimpleCache({ User: {} });
const User = cache.init(model);
const stub = sinon.stub(User, 'findOne').resolves({ username: 'foo' });
sinon.stub(User, 'findOne').resolves({ username: 'foo' });
const result1 = await User.findOne({ where: { username: 'foo' } });
const result2 = await User.findOne({ where: { username: 'foo' } });
expect(result1).to.be.deep.equal({ username: 'foo' });
expect(result2).to.be.deep.equal({ username: 'foo' });
expect(stub.calledOnce).to.be.true;
expect(User.findOne.calledOnce).to.be.true;
User.findOne.restore();
});
});

0 comments on commit 7b0ebc9

Please sign in to comment.