2016-07-09 100 views
1

我有,其基於客戶端的身份驗證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有效。

我想在這裏存儲數據庫調用以解析爲用戶名。但它不工作,無論我嘗試什麼

我試過兩個庫sinonStubPromisesinon-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上下文。不知道爲什麼。

+0

必須是存根的東西,因爲pg-promise本身提供100%的測試覆蓋率沒有問題。你看過它自己測試的方式嗎?也許這將有所幫助;) –

回答

0

我不能說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(); 
    }); 
}); 
+0

我不知道爲什麼它仍然給我一個錯誤..可能是因爲db.one本身是一個承諾對象,主承諾函數不能捕獲.then方法嗎? – Kannaj

+0

我有同樣的問題,我試過這個。仍然超時。任何人設法解決這個問題? – ChickenWing24