Reputation: 6606
I have a promise function which performs an authentication based on the clients cookie
const getInitialState = (id_token) => {
let initialState;
return new Promise((resolve,reject) => {
if(id_token == null){
initialState = {userDetails:{username: 'Anonymous',isAuthenticated: false}}
resolve(initialState)
}else{
var decoded = jwt.verify(JSON.parse(id_token),'rush2112')
db.one('SELECT * FROM account WHERE account_id = $1',decoded.account_id)
.then(function(result){
console.log('result is : ',result)
initialState = {userDetails:{username:result.username,isAuthenticated:true}}
resolve(initialState)
})
.catch(function(err){
console.log('There was something wrong with the token',e)
reject('There was an error parsing the token')
})
}
})
}
getInitialState is a promise object which calls a database function(another promise object) if the cookie is valid.
I want to stub the db call here to resolve to a username. But its not working no matter what i try
i tried two libraries sinonStubPromise
and sinon-as-promised
. But both seem to result in a timeout error which tells me that the db
function isnt getting resolved
I believe i'm not stubbing the db function properly
these are the various ways i've tried
stub2 = sinon.stub(db,'one')
stub2.returnsPromise().resolves({username:'Kannaj'})
or
sinon.stub(db,'one').returns({username:'Kannaj'})
or
sinon.stub(db,'one')
.withArgs('SELECT * FROM account WHERE account_id = $1',1)
.returns({username:'Kannnaj'})
or
let db = sinon.stub(db).withArgs('SELECT * FROM account WHERE account_id = $1',1).returns({username:'Kannnaj'})
all lead to a timeout error from mocha
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
this is my entire test function
it('should return a valid user if id_token is valid',function(){
id_token = '{"account_id":1}'
console.log('stub1: ',stub1(), typeof(stub1))
console.log('stub2 : ',stub2,typeof(stub2))
// my attempts here
return expect(getInitialState(id_token)).to.eventually.be.true
})
For some reason , i believe mocha/sinon is loosing the pg-promise context as soon as it calls db.any . not sure why.
Upvotes: 1
Views: 4071
Reputation: 1199
I can't speak to sinon-as-promised
or sinonStubPromise
, but you don't need them to accomplish something like this.
const sinon = require('sinon');
const chai = require('chai');
chai.use(require('chai-as-promised'));
const expect = chai.expect;
// real object
const db = {
one: function () {
// dummy function
}
};
// real function under test
function foo () {
return db.one('SELECT * FROM account WHERE account_id = $1');
}
describe('foo', function () {
beforeEach(function () {
sinon.stub(db, 'one')
.withArgs('SELECT * FROM account WHERE account_id = $1')
.returns(Promise.resolve({username: 'Kannaj'}));
});
it('should not timeout', function () {
return expect(foo())
.to
.eventually
.eql({username: 'Kannaj'});
});
afterEach(function () {
db.one.restore();
});
});
Upvotes: 1