2017-08-18 28 views
1

我正在使用nockmocha/chai環境中攔截我的http請求。另外我使用supertestsupertest-chai來查詢我自己的express服務器。像這樣:nock:回覆不是函數

從'mocha'導入{it}; import chai,{should} from'chai';

import request from 'supertest'; 
import supertestChai from 'supertest-chai'; 
import Joi from 'joi'; 
import chaiJoi from 'chai-joi'; 
// others 

function itRespondsTo({ url, response, description, parameters = {} }) { 
    const maxAge = parameters.maxAge || serverConfig.defaultCacheAge; 
    const params = parameters ? `${Object.entries(parameters).map(([name, val]) => `&${name}=${val}`).join('&')}` : ''; 
    const path = `/oembed?url=${encodeURIComponent(url)}${params}`; 
    const desc = description || `/oembed?url=${url}${params}`; 
    it(`should respond to ${desc}`, (done) => { 
    request(server) 
     .get(path) 
     .expect(200) 
     .expect('Content-Type', /json/) 
     .expect('Access-Control-Allow-Methods', 'GET') 
     .expect('Cache-Control', `public, max-age=${maxAge}`) 
     .expect(res => Object.values(OEMBED_TYPES).should.include(res.body.type)) // [1] 
     .expect(res => Joi.validate(res.body, OEMBED_SCHEMAS[res.body.type]).should.validate) 
     .expect(response) 
     .end(done); 
    }); 
} 

describe('YouTube endpoint',() => { 
    beforeEach(() => { 
    nock(/youtube\.com/) 
     .reply(200, remoteResponse); 
    }); 

    afterEach(() => { 
    nock.restore(); 
    }); 

    itRespondsTo({ url: 'https://youtu.be/m4hklkGvTGQ', response }); 
    itRespondsTo({ url: 'https://www.youtube.com/embed/m4hklkGvTGQ', response }); 
    itRespondsTo({ url: 'https://www.youtube.com/watch?v=m4hklkGvTGQ', response }); 
    itRespondsTo({ url: 'https://www.youtube.com/?v=m4hklkGvTGQ', response }); 
}); 

當我運行我的測試中,itRespondsTo第一個電話總是會引發錯誤:

1) YouTube endpoint "before each" hook for "should respond to /oembed?url= https://youtu.be/m4hklkGvTGQ ":

TypeError: nock.reply is not a function

它將永遠是itRespondsTo第一個電話。如果我刪除了第一個呼叫,下一個呼叫將拋出錯誤等。我不知道爲什麼會發生這種情況。

回答

1

我發現我得到一個錯誤的原因。我不得不在get之間:

nock('https://www.youtube.com') 
    .get('/oembed') 
    .query(true) 
    .reply(200, remoteResponse);