superagent-mock中文文档|superagent-mock js中文教程|解析
安装命令:npm i superagent-mock
超级代理模拟
超级代理插件允许通过基于请求的 URL 返回数据装置来模拟 HTTP 调用。
查看这篇文章,了解我们为什么在 Bedrock Streaming 中使用 superagent-mock。
安装
使用npm安装:npm install superagent-mock
用纱线安装:yarn add superagent-mock
要求
节点 >= 8.0 超级代理 >= ^3.6.0
用法
首先,您必须在配置文件中定义要模拟的 URL:
// ./superagent-mock-config.js file
module.exports = [
{
/**
* regular expression of URL
*/
pattern: 'https://domain.example(.*)',
/**
* returns the data
*
* @param match array Result of the resolution of the regular expression
* @param params object sent by 'send' function
* @param headers object set by 'set' function
* @param context object the context of running the fixtures function
*/
fixtures: function (match, params, headers, context) {
/**
* Returning error codes example:
* request.get('https://domain.example/404').end(function(err, res){
* console.log(err); // 404
* console.log(res.notFound); // true
* })
*/
if (match[1] === '/404') {
throw new Error(404);
}
/**
* Checking on parameters example:
* request.get('https://domain.example/hero').send({superhero: "superman"}).end(function(err, res){
* console.log(res.body); // "Your hero: superman"
* })
*/
if (match[1] === '/hero') {
if(params['superhero']) {
return 'Your hero:' + params['superhero'];
} else {
return 'You didnt choose a hero';
}
}
/**
* Checking on headers example:
* request.get('https://domain.example/authorized_endpoint').set({Authorization: "9382hfih1834h"}).end(function(err, res){
* console.log(res.body); // "Authenticated!"
* })
*/
if (match[1] === '/authorized_endpoint') {
if(headers['Authorization']) {
return 'Authenticated!';
} else {
throw new Error(401); // Unauthorized
}
}
/**
* Cancelling the mocking for a specific matched route example:
* request.get('https://domain.example/server_test').end(function(err, res){
* console.log(res.body); // (whatever the actual server would have returned)
* })
*/
if (match[1] === '/server_test') {
context.cancel = true; // This will cancel the mock process and continue as usual (unmocked)
return null;
}
/**
* Delaying the response with a specific number of milliseconds:
* request.get('https://domain.example/delay_test').end(function(err, res){
* console.log(res.body); // This log will be written after the delay time has passed
* })
*/
if (match[1] === '/delay_test') {
context.delay = 3000; // This will delay the response by 3 seconds
return 'zzZ';
}
/**
* Mocking progress events:
* request.get('https://domain.example/progress_test')
* .on('progress', function (e) { console.log(e.percent + '%'); })
* .end(function(err, res){
* console.log(res.body); // This log will be written after all progress events emitted
* })
*/
if (match[1] === '/progress_test') {
context.progress = {
parts: 3, // The number of progress events to emit one after the other with linear progress
// (Meaning, loaded will be [total/parts])
delay: 1000, // [optional] The delay of emitting each of the progress events by ms
// (default is 0 unless context.delay specified, then it's [delay/parts])
total: 100, // [optional] The total as it will appear in the progress event (default is 100)
lengthComputable: true, // [optional] The same as it will appear in the progress event (default is true)
direction: 'upload' // [optional] superagent adds 'download'/'upload' direction to the event (default is 'upload')
};
return 'Hundred percent!';
}
},
/**
* returns the result of the GET request
*
* @param match array Result of the resolution of the regular expression
* @param data mixed Data returns by `fixtures` attribute
*/
get: function (match, data) {
return {
body: data
};
},
/**
* returns the result of the POST request
*
* @param match array Result of the resolution of the regular expression
* @param data mixed Data returns by `fixtures` attribute
*/
post: function (match, data) {
return {
status: 201
};
}
},
...
];
然后使用插件:
// ./server.js file
var request = require('superagent');
var config = require('./superagent-mock-config');
// Before tests
var superagentMock = require('superagent-mock')(request, config);
...
// After tests
superagentMock.unset();
支持的方法
支持所有请求方法(get、put、post 等)。
每个请求方法模拟都必须在配置文件中声明。否则,使用该callback
方法。
日志记录
您可以通过在初始化时传递回调函数来监视是否已被 superagent-mock 拦截的每个调用。
// ./server.js file
var request = require('superagent');
var config = require('./superagent-mock-config');
var logger = function(log) {
console.log('superagent call', log);
};
// Before tests
var superagentMock = require('superagent-mock')(request, config, logger);
...
// After tests
superagentMock.unset();
将使用包含以下信息的对象调用回调函数
- data : 与
superagent.send
函数一起使用的数据 - headers :
superagent.set
函数给出的头数组 - matcher :正则表达式匹配在提供的配置中定义的当前 url
- url : 调用超级代理的 url
- method : 用于调用的 HTTP 方法
- timestamp : superagent 调用的时间戳
- mocked : true 如果调用被 superagent mock 模拟,false 如果它使用 superagent real 方法
开发脚本
要运行单位测试:yarn test
。
检查代码样式:yarn lint
.
构建代码:yarn build
.
学分
由Bedrock Streaming的 Cytron 团队开发。用Jest测试。
执照
项目issue数量: 6