supertest中文文档|中文示例
超级测试
通过superagent使 HTTP 断言变得容易。
关于
此模块的动机是为测试 HTTP 提供高级抽象,同时仍允许您下拉到superagent 提供的低级 API。
入门
将 SuperTest 作为 npm 模块安装,并将其作为开发依赖项保存到 package.json 文件中:
npm install supertest --save-dev
安装后,现在只需调用即可引用 require('supertest');
例子
您可以传递http.Server
, 或Function
to request()
– 如果服务器尚未侦听连接,那么它会为您绑定到一个临时端口,因此无需跟踪端口。
SuperTest 适用于任何测试框架,这是一个根本不使用任何测试框架的示例:
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
这是 mocha 的示例,请注意如何直接传递done
给任何.expect()
调用:
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
您可以使用auth
方法以与超级代理中相同的方式传递 HTTP 用户名和密码:
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.auth('username', 'password')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
上述语句需要注意的一点是,如果您不添加状态代码 expect (即.expect(302)
),则 superagent 现在将任何 HTTP 错误(除 2XX 响应代码之外的任何内容)作为第一个参数发送到回调。
如果您使用的.end()
方法.expect()
断言失败不会抛出 – 它们会将断言作为错误返回给.end()
回调。为了使测试用例失败,您需要重新抛出或传递err
给done()
,如下所示:
describe('POST /users', function() {
it('responds with json', function(done) {
request(app)
.post('/users')
.send({name: 'john'})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function(err, res) {
if (err) return done(err);
return done();
});
});
});
您还可以使用承诺:
describe('GET /users', function() {
it('responds with json', function(done) {
return request(app)
.get('/users')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then(response => {
assert(response.body.email, 'foo@bar.com')
done();
})
.catch(err => done(err))
});
});
期望按定义的顺序运行。此特性可用于在执行断言之前修改响应正文或标头。
describe('POST /user', function() {
it('user.name should be an case-insensitive match for "john"', function(done) {
request(app)
.post('/user')
.send('name=john') // x-www-form-urlencoded upload
.set('Accept', 'application/json')
.expect(function(res) {
res.body.id = 'some fixed id';
res.body.name = res.body.name.toLowerCase();
})
.expect(200, {
id: 'some fixed id',
name: 'john'
}, done);
});
});
你可以用 superagent 做的任何事情,你都可以用 supertest 做 – 例如多部分文件上传!
request(app)
.post('/')
.field('name', 'my awesome avatar')
.attach('avatar', 'test/fixtures/avatar.jpg')
...
不需要每次都传递应用程序或 url,如果您正在测试同一个主机,您可以简单地使用初始化应用程序或 url 重新分配请求变量,Test
每次request.VERB()
调用都会创建一个新的。
request = request('http://localhost:5555');
request.get('/').expect(200, function(err){
console.log(err);
});
request.get('/').expect('heya', function(err){
console.log(err);
});
下面是一个 mocha 示例,展示了如何持久化请求及其 cookie:
const request = require('supertest');
const should = require('should');
const express = require('express');
const cookieParser = require('cookie-parser');
describe('request.agent(app)', function() {
const app = express();
app.use(cookieParser());
app.get('/', function(req, res) {
res.cookie('cookie', 'hey');
res.send();
});
app.get('/return', function(req, res) {
if (req.cookies.cookie) res.send(req.cookies.cookie);
else res.send(':(')
});
const agent = request.agent(app);
it('should save cookies', function(done) {
agent
.get('/')
.expect('set-cookie', 'cookie=hey; Path=/', done);
});
it('should send cookies', function(done) {
agent
.get('/return')
.expect('hey', done);
});
});
还有一个例子是由文件agency.js引入的
这是一个示例,其中在请求上设置了 2 个 cookie。
agent(app)
.get('/api/content')
.set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo'])
.send()
.expect(200)
.end((err, res) => {
if (err) {
return done(err);
}
expect(res.text).to.be.equal('hey');
return done();
});
应用程序接口
您可以使用任何SuperAgent的方法,包括.write()
,.pipe()
等,并在执行断言.end()
回调较低级别的需求。
.expect(状态[, fn])
断言响应status
代码。
.expect(状态,身体[,fn])
断言响应status
代码和body
.
.expect(body[, fn])
body
使用字符串、正则表达式或解析的正文对象断言响应文本。
.expect(field, value[, fn])
field
value
使用字符串或正则表达式断言标头。
.expect(function(res) {})
传递自定义断言函数。它将获得响应对象进行检查。如果检查失败,则抛出错误。
request(app)
.get('/')
.expect(hasPreviousAndNextKeys)
.end(done);
function hasPreviousAndNextKeys(res) {
if (!('next' in res.body)) throw new Error("missing next key");
if (!('prev' in res.body)) throw new Error("missing prev key");
}
.end(fn)
执行请求并调用fn(err, res)
.
笔记
灵感来自api-easy减去誓言耦合。
执照
麻省理工学院