如果你想在Node.js中实现一个RESTful API,使用JSON格式的话,有哪些好的选项用于编写集成测试套件呢?
这个测试套件应该执行测试场景,通常包括将数据库设置为已知状态 (可能通过POST请求),并运行一系列涉及GET、POST、PUT和DELETE请求的测试,检查返回的状态码和响应。
如果你想在Node.js中实现一个RESTful API,使用JSON格式的话,有哪些好的选项用于编写集成测试套件呢?
这个测试套件应该执行测试场景,通常包括将数据库设置为已知状态 (可能通过POST请求),并运行一系列涉及GET、POST、PUT和DELETE请求的测试,检查返回的状态码和响应。
有几种单元测试框架可供选择。
我将展示使用 expresso 和 vows 的示例。
var assert = require('assert'),
http = require('http'),
server = getServer(); // get an instance of the HTTPServer
assert.response(server, {
'url': '/'
}, {
'body': "test body",
'status': "200"
});
以下是使用 vows-is 的示例:
var is = require("vows-is");
is.config({
server: {
"factory": createServer,
"kill": destroyServer,
"uri": "http://localhost:4000"
}
})
is.suite("integration tests").batch()
.context("a request to GET /")
.topic.is.a.request("GET /")
.vow.it.should.have.status(200)
.vow.it.should.have
.header("content-type", "text/html; charset=utf-8")
.context("contains a body that")
.topic.is.property('body')
.vow.it.should.be.ok
.vow.it.should.include.string("hello world")
.suite().run({
reporter: is.reporter
}, function() {
is.end()
});
vows-is是建立在vows之上的一个薄抽象层,使测试变得更加容易。
然而,由于vows-is正在积极开发中,因此使用时需自行承担风险。