[英]How to properly stub and test a function using sinon
我有这个基本方法,可以接受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对象)
到目前为止,我已经尝试过了。 存根db调用会返回此错误,我发现这确实很模糊
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是有效的,是否发送回适当的对象
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
})
您需要重写某些pg-promises默认值以重写特定的方法
特别是将noLocking = true设置为
const pgp = require('pg-promise')({noLocking:true})
UPDATE
来自pg-promise作者。 这是正确的方法。 请参阅选项noLocking :
如果此规定妨碍了使用模拟框架进行测试,则可以通过在选项中设置noLocking = true来强制库停用大多数锁。
它应该是
sinon.stub(db, 'one').resolves();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.