用于testingExpress应用程序的状态交互

我用express写了一个简单的JSON API,我试图用mocha做一些黑盒testing。 通过对API进行testing,需要对不同的用户进行身份validation,因此每个针对特定function的testing都至less由两个请求组成:一个login操作和一个或多个validation请求,用于testing实际function。

我还没有find类似于django.test.client库来模拟HTTP客户端和服务器之间的有状态交互。 Supertest似乎很受欢迎,但与djangotesting客户端相比,它是非常低级的。 这是我将如何写一个简单的authenticationtesting(请原谅我的咖啡标记):

 it 'should return a 200 OK', (done) -> supertest(server.app) .post('/login') .send("username=xxx&password=pass") .end (err, res) -> res.should.have.status(200) supertest(server.app) .get('/api/users') .set('cookie', res.headers['set-cookie'][0]) .expect(200, done) 

这真的是最干净的方式来执行交互? 有什么图书馆可以帮助我解决asynchronous问题(这不是我需要的东西,而是99%的情况下,testing的简单序列化,callback只是混淆)和有状态? 一些会这样的事情:

 it 'should rock', (done) -> myCoolLibrary [ -> @post '/login', {username: "xxx", password: "pass"}, (err, res) => res.should.have.status 200 @done() , -> @get '/api/users', (err, res) => res.should.have.status 200 @done() ] 

如果没有类似的东西,我应该自己写:-)对环境的依赖是因为我现在使用了太多的ZappaJS,并且感谢CoffeeScript的胖箭头,这根本就不是一个坏习惯。

听起来你可以从僵尸中受益。 它模拟浏览器并在请求之间保存cookie和会话数据。

它还为您提供更强大的function,例如允许您填写表单并提交它们。

一个典型的testing看起来像这样:

 var Browser = require('zombie') , browser = new Browser({site:'http://yoursite.com'}); describe('page',function(){ before(function(done){ browser.visit('/loginpage',done); }); it('should return a 200 page',function(done){ browser.fill('username','xxx'); browser.fill('password','pass'); //assuming your form points to /login browser.pressButton('button[type="submit"]'),function(){ assert(browser.success); //status code is 2xx }).then(done,done); //call the done handler after promise is fulfilled }); it('should rock',function(done){ browser.visit('/api/users',function(){ assert(browser.success); }).then(done,done); }); 

作为使asynchronous代码更清晰可读的更一般的解决scheme,请查看asynchronous。 https://github.com/caolan/async

async.serial只会做你所需要的,但我会特别推荐async.auto,它允许你以一种明确的方式将各个步骤与它们的依赖链接在一起。

最后我写了一个小图书馆,这个图书馆与我的“理想”例子非常接近。 现在它不值得拥有自己的软件包,所以我只是把它放在一个要点上:

https://gist.github.com/BruceBerry/5485917

我无法用超强和超级的方式进行有状态的交互,所以我只是放弃了他们的请求。 主要区别似乎是你不能链接期望,你必须在callback中做所有的testing,但是如果你已经在使用另一个testing库如should.js