【发布时间】:2016-07-09 14:38:42
【问题描述】:
我有一个基于客户端 cookie 执行身份验证的 promise 函数
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 是一个 promise 对象,如果 cookie 有效,它会调用数据库函数(另一个 promise 对象)。
我想在此处存根 db 调用以解析为用户名。但无论我尝试什么,它都不起作用
我尝试了两个库 sinonStubPromise 和 sinon-as-promised。但两者似乎都导致超时错误,告诉我db 函数没有得到解决
我相信我没有正确地存根 db 函数
这些是我尝试过的各种方法
stub2 = sinon.stub(db,'one')
stub2.returnsPromise().resolves({username:'Kannaj'})
或
sinon.stub(db,'one').returns({username:'Kannaj'})
或
sinon.stub(db,'one')
.withArgs('SELECT * FROM account WHERE account_id = $1',1)
.returns({username:'Kannnaj'})
或
let db = sinon.stub(db).withArgs('SELECT * FROM account WHERE account_id = $1',1).returns({username:'Kannnaj'})
都导致mocha超时错误
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
这是我的全部测试功能
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
})
出于某种原因,我相信 mocha/sinon 在调用 db.any 时就会失去 pg-promise 上下文。不知道为什么。
【问题讨论】:
-
必须是存根的东西,因为
pg-promise本身提供了 100% 的测试覆盖率而没有问题。你见过它测试自己的方式吗?也许这会有所帮助;)
标签: javascript promise mocha.js sinon pg-promise