使用茉莉花来testingExpress.js
我正在学习Node.js和Express框架。 我是茉莉花的忠实粉丝。 所以我想尽可能用茉莉花,但是我找不到用茉莉花testingExpress的好方法。 例如,我应该如何testingapp.js中的路线?
如果我在app.js中有这条路线:
app.get('/', function(req, res) { ... });
我如何使用茉莉花来testing它?
Jasmine-node使得用jasmine和node.js很容易。 他们的网站上有一些例子。 另一个例子可以从http://blog.drewolson.org/post/14684497867/find
你应该尝试一下http://frisbyjs.com/
我没有机会使用它,但是当我正在寻找解决同样问题的方法时,这是我能find的最好的方法。
由于Jasmine 2在Node.js环境中使用Jasmine非常简单。 为了testing快速应用程序,我build议使用Jasmine结合supertest 。
下面是这样一个testing的样子:
项目/规格/ 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()); }); }); });
一些先决条件:
- 在您的项目中安装Jasmine v2作为开发依赖项:
npm i -D jasmine@2
- 在项目中安装supertest v3作为开发依赖项:
npm i -D supertest@3
- 使用
jasmine init
创build一个初始的Jasmineconfiguration(注意:如果你还没有运行这个命令,你需要先安装Jasmine) - 创build一个以“Spec.js”结尾的规范(如
ServerSpec.js
)
以下是Jasmineconfiguration的外观:
项目/规格/支持/ jasmine.json
{ "helpers": [ "helpers/**/*.js" ], "random": false, "spec_dir": "spec", "spec_files": [ "**/*[sS]pec.js" ], "stopSpecOnExpectationFailure": false }
要运行你的规范(testing套件),只需将其添加到你的npm脚本并执行npm test
(或者只是npm t
):
"scripts": { "test": "jasmine" },
你可以使用超级茉莉花,但你只需要手动传递错误。 关于GitHub项目的一个问题刚才已经提到。
你可以尝试使用与Jasmine的承诺。 它为我工作: https : //github.com/WhoopInc/supertest-as-promised
这里有些例子:
也许你可以尝试超级 摩卡 。
这是一个简单的例子:
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); }) })