2017-06-21 47 views
2

我正在使用Koa2和Request爲我的第一個真實世界節點項目製作RESTful API調用第三方。 Koa服務本身相對簡單,但我正在嘗試使用Jest來編寫它的集成測試。我發現examples of using Jest with Supertest/Superagent,但我無法找到如何使用僅作爲HTTP客戶端的Jest和Request來編寫等效測試。下面是玩笑/ Supertest例如...如何利用請求集成測試異步Koa節點API

const request = require('supertest'); 
const app = require('../../src/app') 
describe('Test the root path',() => { 
    test('It should response the GET method', async() => { 
     const response = await request(app).get('/'); 
     expect(response.statusCode).toBe(200); 
    }); 
}) 

好像我應該能夠只使用要求做supertest/SuperAgent的在這裏做同樣的事情,但我不能找到任何例子。感謝您的建議!

回答

0

Supertest看起來很神奇,因爲你可以通過它app,並以某種方式正常工作。

在引擎蓋下,Supertest只是開始監聽並配置底層請求,以使用該地址作爲基礎URL。

我在這裏使用Axios作爲例子,我沒有使用Request,但它應該很容易調整。

const axios = require('axios') 
const app = require('../../src/app') 
const server = app.listen() // random port 

const url = `http://127.0.0.1:${server.address().port}` 

const request = axios.create({ baseURL: url }) 

describe('Test the root path',() => { 
    test('It should response the GET method', async() => { 
     const response = await request.get('/') 
     expect(response.statusCode).toBe(200) 
    }); 
})