gpt4 book ai didi

javascript - 如何使用 sinon 正确 stub 和测试函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:39:57 26 4
gpt4 key购买 nike

我有这个接受 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')
})
}
})
}

因为这是一个 promise - 我正在使用 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 和外部数据库调用(它本身是另一个 promise 对象)

到目前为止我已经试过了。 stub 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)

我猜它不允许我 stub 整个数据库对象。我还能怎么处理这个?我只希望 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
})

最佳答案

您需要覆盖一些 pg-promises 默认值以覆盖特定方法

特别设置 noLocking=true

const pgp = require('pg-promise')({noLocking:true})

UPDATE-1

来自 pg-promise作者。这是正确的做法。参见选项 noLocking :

If this provision gets in the way of using a mock-up framework for your tests, you can force the library to deactivate most of the locks by setting noLocking = true within the options.

UPDATE-2

接口(interface)锁定已在 pg-promise v11 中完全移除。选项 noLocking 不再存在。

关于javascript - 如何使用 sinon 正确 stub 和测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38253613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com