gpt4 book ai didi

javascript - 如何正确 stub 作为另一个 Promise 一部分的 Promise 对象

转载 作者:行者123 更新时间:2023-11-28 05:48:27 26 4
gpt4 key购买 nike

我有一个 Promise 函数,它根据客户端 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 是一个 Promise 对象,如果 cookie 有效,它会调用数据库函数(另一个 Promise 对象)。

我想在此处 stub 数据库调用以解析为用户名。但无论我怎么尝试它都不起作用

我尝试了两个库sinonStubPromisesinon-as-promised。但两者似乎都会导致超时错误,这告诉我 db 函数没有得到解决

我相信我没有正确地 stub 数据库函数

这些是我尝试过的各种方法

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 上下文。不知道为什么。

最佳答案

我无法与 sinon-as-promisedsinonStubPromise 交谈,但你不需要它们来完成这样的事情。

const sinon = require('sinon');
const chai = require('chai');
chai.use(require('chai-as-promised'));
const expect = chai.expect;

// real object
const db = {
one: function () {
// dummy function
}
};

// real function under test
function foo () {
return db.one('SELECT * FROM account WHERE account_id = $1');
}

describe('foo', function () {
beforeEach(function () {
sinon.stub(db, 'one')
.withArgs('SELECT * FROM account WHERE account_id = $1')
.returns(Promise.resolve({username: 'Kannaj'}));
});

it('should not timeout', function () {
return expect(foo())
.to
.eventually
.eql({username: 'Kannaj'});
});

afterEach(function () {
db.one.restore();
});
});

关于javascript - 如何正确 stub 作为另一个 Promise 一部分的 Promise 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38282915/

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