2017-02-26 42 views
0

我注意到,每次我想用superagent運行節點測試時,我都在寫http://localhost帶絕對URL前綴的超級用戶

import superagent from 'superagent'; 

const request = superagent.agent(); 
request 
    .get('http://localhost/whatever') 
    .end((err, res) => { ... }); 

有什麼辦法可以避免localhost部分?

至於我已經是避免請求被硬編碼到主機:

const baseUrl = 'http://localhost:3030'; 

request 
    .get(`${baseUrl}/whatever`) 

但我還是要攜帶baseUrl與代理每次。

回答

0

TL; DR:superagent-absolute確實如此。

詳細:

您可以創建的superagent頂部一個抽象層。

function superagentAbsolute(agent) { 
    return baseUrl => ({ 
    get: url => url.startsWith('/') ? agent.get(baseUrl + url) : agent.get(url), 
    }); 
} 

⬑這將覆蓋agent.get當一開始/

global.request = superagentAbsolute(agent)('http://localhost:3030'); 

現在,你需要做同樣的呼籲:DELETE,HEAD,PATCH,POST和PUT。

https://github.com/zurfyx/superagent-absolute/blob/master/index.js

const OVERRIDE = 'delete,get,head,patch,post,put'.split(','); 
const superagentAbsolute = agent => baseUrl => (
    new Proxy(agent, { 
    get(target, propertyName) { 
     return (...params) => { 
     if (OVERRIDE.indexOf(propertyName) !== -1 
      && params.length > 0 
      && typeof params[0] === 'string' 
      && params[0].startsWith('/')) { 
      const absoluteUrl = baseUrl + params[0]; 
      return target[propertyName](absoluteUrl, ...params.slice(1)); 
     } 
     return target[propertyName](...params); 
     }; 
    }, 
    }) 
); 

或者你可以簡單地使用superagent-absolute

const superagent = require('superagent'); 
const superagentAbsolute = require('superagent-absolute'); 

const agent = superagent.agent(); 
const request = superagentAbsolute(agent)('http://localhost:3030'); 

it('should should display "It works!"', (done) => { 
    request 
    .get('/') // Requests "http://localhost:3030/". 
    .end((err, res) => { 
     expect(res.status).to.equal(200); 
     expect(res.body).to.eql({ msg: 'It works!' }); 
     done(); 
    }); 
});