我有这个接受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){
initialState = {userDetails:{username:result.username,isAuthenticated:true}}
resolve(initialState)
})
.catch(function(err){
console.log('There was something wrong with the token')
reject('There was an error parsing the token')
})
}
})
}
因为这是一个承诺 - 我正在使用chaiAspromised。
我能够使用以下
成功测试第一个条件(cookie未预设) it('should return anonymous user if id_token isnt preset',function(){
let id_token = null
return expect(getInitialState(id_token)).to.eventually.have.deep.property('userDetails.username','Anonymous')
})
然而,我不能/不太确定如何测试第二部分因为它依赖于jwt和外部db调用(它本身是另一个promise对象)
到目前为止我已经尝试过了。对数据库调用进行存根操作会返回此错误,我发现这个错误非常模糊
1) GetInitialState should return a valid user if id_token is valid:
TypeError: Cannot redefine property: connect
at Function.defineProperty (native)
at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:128:24)
at stub (node_modules/sinon/lib/sinon/stub.js:67:26)
at node_modules/sinon/lib/sinon/stub.js:60:25
at node_modules/sinon/lib/sinon/walk.js:28:30
at Array.forEach (native)
at walkInternal (node_modules/sinon/lib/sinon/walk.js:23:45)
at Object.walk (node_modules/sinon/lib/sinon/walk.js:49:20)
at Object.stub (node_modules/sinon/lib/sinon/stub.js:52:23)
at Context.<anonymous> (getInitialState.spec.js:27:11)
我想它不允许我存根整个db对象。我怎么能接近这个?我只想要jwt和db调用都不会抛出任何错误。我只是测试如果cookie是valie
,是否发送了适当的对象 it('should return a valid user if id_token is valid',function(){
sinon.stub(jwt,'verify').returns({username:foo});
sinon.stub(db).resolves() // unsure of what to do here
id_token = ' Foo----bar '
return expect(getInitialState(id_token)).to.eventually.be.true
})
答案 0 :(得分:3)
你需要覆盖一些pg-promises默认值来覆盖特定方法
特别是通过
设置noLocking = trueconst pgp = require('pg-promise')({noLocking:true})
<强>更新强>
来自pg-promise作者。这是正确的方法。请参阅选项noLocking:
如果此规定妨碍了为您的测试使用模型框架,则可以通过在选项中设置noLocking = true来强制库停用大多数锁。
答案 1 :(得分:0)
应该是
sinon.stub(db, 'one').resolves();