如何利用请求集成testingasynchronousKoa节点API

我正在使用Koa2和Request对第三方进行RESTful API调用来处理我的第一个真实世界的Node项目。 Koa服务本身是相对简单的,但我正在尝试使用Jest编写一个集成testing。 我已经find使用Supertest / Superagent的Jest的例子 ,但我无法find如何使用只有Jes​​t和Request作为http客户端编写等效testing。 下面是Jest / Supertest的例子

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在这里做的相同的事情,但我找不到任何例子。 感谢您的build议!

Supertest看起来很神奇,因为你可以将它传递给你的app并以某种方式正常工作。

在引擎盖下,Supertest只是开始监听并configuration底层的请求,使用该地址作为基础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) }); })