NodeJS中axios和supertest的区别 [英] The difference between axios and supertest in NodeJS

查看:18
本文介绍了NodeJS中axios和supertest的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Axios 和 Supertest 都可以向服务器发送 HTTP 请求.但是为什么Supertest用于测试而Axios用于练习API调用?

Both Axios and Supertest can send HTTP requests to a server. But why is Supertest used for testing while Axios is used for practice API calls?

推荐答案

使用 Supertest 而不是像 Axios(或 Supertest 包装的 Superagent)这样的普通请求库:

There are two reasons to use Supertest rather than a vanilla request library like Axios (or Superagent, which Supertest wraps):

  1. 它为您管理启动和绑定应用程序,使其可用于接收请求:

  1. It manages starting and binding the app for you, making it available to receive the requests:

您可以将 http.ServerFunction 传递给 request() - 如果服务器尚未侦听连接,然后它绑定到临时端口,因此无需跟踪端口.

You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.

没有这个,你就必须启动应用程序并自己设置端口.

Without this, you'd have to start the app and set the port yourself.

它添加了 expect 方法,它允许您对响应进行很多常见的断言,而不必自己写出来.例如,而不是:

It adds the expect method, which allows you to make a lot of common assertions on the response without having to write it out yourself. For example, rather than:

// manage starting the app somehow...

axios(whereAppIs + "/endpoint")
  .then((res) => {
    expect(res.statusCode).toBe(200);
  });

你可以写:

request(app)
  .get("/endpoint")
  .expect(200);

这篇关于NodeJS中axios和supertest的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆