2016-06-07 54 views
1

我想測試一個裏面調用供應商中間件函數的中間件函數。中間件是:如何測試依賴其他供應商中間件的快遞中間件?

const expressJwt = require('express-jwt'); 
const validateJwt = expressJwt({ secret: 'whatever' }); 

exports.isAuthenticated = (req, res, next) => { 
    if (req.query && req.query.hasOwnProperty('access_token')) { 
    req.headers.authorization = `Bearer ${req.query.access_token}`; 
    } 

    validateJwt(req, res, next); 
}; 

我試圖創建一個sinon.spy()對象,並把它作爲next參數,但顯然不是叫。

另一種方法我試過是檢查是否存在req.user,因爲express-jwt中間件的目的是爲了驗證和連接userreq對象。沒有這個運氣。

我看過chai-connect的存在,但不知道如何使用它。

任何想法?高度欣賞它!

回答

0

我終於有proxyquirechai-connect做到這一點:

在你的摩卡配置:

chai.use(require('chai-connect-middleware')); 
global.connect = chai.connect; 

在您的測試:

describe('isAuthenticated',() => { 
// Wrap call to chai.connect into a function to use params and return a Promise 
const mockedMiddleware = (changeSecret) => { 
    let oldToken; 
    if (changeSecret) { 
    oldToken = acessToken; 
    acessToken = 'blabalblalba'; 
    } 

    return new Promise((resolve, reject) => { 
    connect.use(middleware.isAuthenticated) 
     .req(req => { 
     req.query = { access_token: acessToken }; 
     }) 
     .next((res) => { 
     acessToken = oldToken; 
     if (res && res.status === 401) { 
      reject(res.message); 
     } else { 
      resolve(); 
     } 
     }) 
     .dispatch(); 
    }); 
}; 

it('should validate correctly',() => 
    mockedMiddleware().should.be.fulfilled 
); 

it('should not validate',() => 
    mockedMiddleware(true).should.be.rejected 
); 
});