简体   繁体   English

如何利用请求集成测试异步Koa Node API

[英]How to utilize Request to integration test async Koa Node API

I'm working on my first real-world Node project using Koa2 and Request for making RESTful API calls to a 3rd party. 我正在使用Koa2和Request进行对第3方的RESTful API调用的第一个实际Node项目。 The Koa service itself is relatively simple, but I'm trying to write an integration test for it using Jest . Koa服务本身相对简单,但是我正在尝试使用Jest为其编写集成测试。 I've found examples of using Jest with Supertest/Superagent , but I cant find how I'd write the equivalent test using ONLY Jest and Request as the http client. 我已经找到了将Jest与Supertest / Superagent结合使用的示例 ,但是我找不到如何使用ONLY Jest和Request作为http客户端编写等效测试的方法。 Below is the Jest/Supertest example... 以下是开玩笑/超级测试示例...

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);
    });
})

It seems like I should be able to just use Request to do the same thing that supertest/superagent is doing here, but I cant find any example. 似乎我应该能够使用Request来执行与supertest / superagent相同的操作,但是我找不到任何示例。 Thanks for suggestions! 感谢您的建议!

Supertest looks magical because you can pass it your app and somehow that just works. Supertest看起来很神奇,因为您可以将它传递给您的app并且以某种方式起作用。

Under the hood, Supertest justs starts listening and configures the underlying request to use the address as a base url. 在后台,Supertest只是开始侦听并配置基础请求以将该地址用作基本URL。

I'm using Axios here as an example, I don't use Request but it should be easy enough to adjust. 我在这里以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)
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM