chai-superagent
使用 Chai 断言的 superagent 集成测试。
功能
- 对
chai-http
的简化分支 - 仅限 esm 模块,支持 node >= 14
- 集成测试请求组合
- 测试 http 应用或外部服务
- 针对常见 http 任务的断言
- chai
expect
和should
接口
安装
$ npm install chai-superagent superagent
插件
像使用其他 Chai 插件一样使用此插件。注意函数调用 - 它接受一个可选参数 { strict }: { strict?: boolean }
。当 strict
为 true 时,断言将断言测试对象是 superagent
Request
、Response
或 Agent
类型的实例。默认值为 true
。
import { use } from 'chai';
import superagent from 'chai-superagent';
use(superagent());
集成测试
像往常一样使用 superagent
,并使用此库中提供的断言来测试响应。
import request from 'superagent';
request
.get('https://#:8000/foo')
.then(res => expect(res).to.have.status(200));
断言
Chai HTTP 模块为 expect
和 should
接口提供了一些断言。
.status (code)
- @param {Number} 状态码
断言响应具有给定的状态。
expect(res).to.have.status(200);
.header (key[, value])
- @param {String} 头部键(不区分大小写)
-
@param _{String RegExp}_ 头部值(可选)
断言 Response
或 Request
对象具有头部。如果提供了值,则会断言与值的相等性。您也可以传递正则表达式来检查。
注意:在 Web 浏览器中运行时,同源策略 仅允许 Chai HTTP 读取 某些头部,这会导致断言失败。
expect(req).to.have.header('x-api-key');
expect(req).to.have.header('content-type', 'text/plain');
expect(req).to.have.header('content-type', /^text/);
.headers
断言 Response
或 Request
对象具有头部。
注意:在 Web 浏览器中运行时,同源策略 仅允许 Chai HTTP 读取 某些头部,这会导致断言失败。
expect(req).to.have.headers;
.json / .text / .html
断言 Response
或 Request
对象具有给定的内容类型。
expect(req).to.be.json;
expect(req).to.be.html;
expect(req).to.be.text;
.charset
断言 Response
或 Request
对象具有给定的字符集。
expect(req).to.have.charset('utf-8');
.redirect
断言 Response
对象具有重定向状态码。
expect(res).to.redirect;
expect(res).to.not.redirect;
.redirectTo
-
@param _{String RegExp}_ 位置 URL
断言 Response
对象重定向到给定的位置。
expect(res).to.redirectTo('http://example.com');
expect(res).to.redirectTo(/^\/search\/results\?orderBy=desc$/);
.param
- @param {String} 参数名
- @param {String} 参数值
断言 Request
对象具有具有给定键的查询字符串参数(可选)等于值
expect(req).to.have.param('orderby');
expect(req).to.have.param('orderby', 'date');
expect(req).to.not.have.param('limit');
.cookie
- @param {String} 参数名
- @param {String} 参数值
断言 Request
或 Response
对象具有具有给定键的 cookie 头部(可选)等于值
expect(req).to.have.cookie('session_id');
expect(req).to.have.cookie('session_id', '1234');
expect(req).to.not.have.cookie('PHPSESSID');
expect(res).to.have.cookie('session_id');
expect(res).to.have.cookie('session_id', '1234');
expect(res).to.not.have.cookie('PHPSESSID');
许可证
请参阅 LICENSE 文件以了解许可证权利和限制(MIT)。