我有,其基於客戶端的身份驗證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是一個承諾對象,調用數據庫功能的承諾函數(另一個承諾的一部分對象)如果cookie有效。
我想在這裏存儲數據庫調用以解析爲用戶名。但它不工作,無論我嘗試什麼
我試過兩個庫sinonStubPromise
和sinon-as-promised
。但似乎都導致超時錯誤,告訴我,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'})
都可能導致超時錯誤,從摩卡
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
})
出於某種原因,我相信摩卡/興農是隻要調用db.any就會丟失pg-promise上下文。不知道爲什麼。
必須是存根的東西,因爲pg-promise本身提供100%的測試覆蓋率沒有問題。你看過它自己測試的方式嗎?也許這將有所幫助;) –