我正在学习Node.js和Express框架。我非常喜欢Jasmine。因此,我希望能够在任何时候都使用Jasmine进行测试,但是,我无法找到一个好的方式来使用Jasmine测试Express。例如,我应该如何测试app.js中的路由?
如果我在app.js中有这个路由:
app.get('/', function(req, res) {
...
});
我如何使用Jasmine来测试它?
自从Jasmine 2推出以来,在Node.js环境中使用Jasmine非常简单。为了使用Jasmine测试express应用程序,我建议与supertest结合使用。
以下是这样一个测试的样子:
project/spec/ServerSpec.json
const request = require('supertest');
const app = require('../app');
describe('Server', () => {
describe('REST API v1', () => {
it('returns a JSON payload', (done) => {
request(app)
.get('/rest/service/v1/categories')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8')
.end((error) => (error) ? done.fail(error) : done());
});
});
});
一些前提条件:
npm i -D jasmine@2
npm i -D supertest@3
jasmine init
创建一个初始的Jasmine配置(注:如果您还没有全局安装Jasmine,则需要先进行安装才能运行此命令)ServerSpec.js
)以下是Jasmine配置的示例:
project/spec/support/jasmine.json
{
"helpers": [
"helpers/**/*.js"
],
"random": false,
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"stopSpecOnExpectationFailure": false
}
要运行您的规范(测试套件),只需将此添加到 npm脚本 中并执行npm test
(或仅执行npm t
):
"scripts": {
"test": "jasmine"
},
Jasmine-node使得在node.js中使用jasmine变得简单。他们的网站上有一些示例。另一个示例可以在http://blog.drewolson.org/post/14684497867/ web.archive.org中找到。
这里有一个简单的例子:
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(200, { name: 'toto' });
});
describe('GET /user', function(){
it('should respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', 'json')
.expect(200, done);
})
})