如何利用请求集成测试异步Koa节点API
问题描述:
我正在使用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的在这里做同样的事情,但我不能找到任何例子。感谢您的建议!
答
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)
});
})