2017-03-23 89 views
0

我一直在編寫一些單元測試,我注意到我似乎無法找到測試異步函數的好方法。所以我找到了nock。它看起來很酷,只有它工作。我清楚地失去了一些東西......如何獲得nock的響應

import nock from 'nock'; 
import request from 'request'; 

const profile = { 
    name: 'John', 
    age: 25 
}; 

const scope = nock('https://mydomainname.local') 
    .post('/api/send-profile', profile) 
    .reply(200, {status:200}); 

request('https://mydomainname.local/api/send-profile').on('response', function(request) { 
    console.log(typeof request.statusCode); // this never hits 
    expect(request.statusCode).to.equal.(200); 
}); 

request從未發生過,所以我怎麼可以測試是否箭扣實際返回{status:200}?我也試過fetch和正常http調用。這讓我覺得這是我的諾克碼?提前謝謝你的幫助!

回答

1

Nock不返回{status:200},因爲它攔截POST請求,但request語句正在發送GET請求。

看來你想攔截POST請求與指定profile?代碼將是:

var nock = require('nock'); 
var request = require('request'); 

const profile = { 
    name: 'John', 
    age: 25 
}; 

const scope = nock('https://mydomainname.local') 
    .post('/api/send-profile', profile) 
    .reply(200, {status:200}); 

request.post('https://mydomainname.local/api/send-profile', {json: {name: 'John', age: 25}}).on('response', function(request) { 
    console.log(request.statusCode); // 200 
});