我有一个express服务器,我正在使用vows测试它。我想从vows测试套件中运行服务器,这样我就不需要让它在后台运行,以便测试套件工作,然后我只需创建一个运行服务器并隔离测试它的蛋糕任务即可。
在server.coffee中,我创建了(express)服务器,对其进行了配置,设置了路由,并调用了app.listen(端口),如下所示:
# Express - setup
express = require 'express'
app = module.exports = express.createServer()
# Express - configure and set up routes
app.configure ->
app.set 'views', etc....
....
# Express - start
app.listen 3030在我的简单routes-test.js中,我有:
vows = require('vows'),
assert = require('assert'),
server = require('../app/server/server');
// Create a Test Suite
vows.describe('routes').addBatch({
'GET /' : respondsWith(200),
'GET /401' : respondsWith(401),
'GET /403' : respondsWith(403),
'GET /404' : respondsWith(404),
'GET /500' : respondsWith(500),
'GET /501' : respondsWith(501)
}).export(module);其中respondsWith(code)在功能上与vows文档中的功能相似...
当我在上面的测试中require服务器时,它会自动开始运行服务器,测试运行并通过,这很棒,但我觉得我做的不是“正确”的方式。
我无法控制服务器何时启动,如果我想将服务器配置为指向'test‘环境而不是默认环境,或者更改im测试时的默认日志记录级别,会发生什么?
另外,我打算将我的誓言转换为Coffeescript,但现在它都在js中,因为我正从文档中学习模式!
发布于 2011-08-17 19:35:17
这是一个有趣的问题,因为昨晚我确实做了你想做的事情。我有一个小的CoffeScript Node.js应用程序,它恰好是像你展示的那样编写的。然后,我对它进行了重构,创建了以下app.coffee
# ... Imports
app = express.createServer()
# Create a helper function
exports.start = (options={port:3000, logfile:undefined})->
# A function defined in another module which configures the app
conf.configure app, options
app.get '/', index.get
# ... Other routes
console.log 'Starting...'
app.listen options.port现在我有了一个简单的index.coffee (相当于您的server.coffee):
require('./app').start port:3000然后,我使用Jasmine-node和Zombie.js编写了一些测试。测试框架不同,但原则是相同的:
app = require('../../app')
# ...
# To avoid annoying logging during tests
logfile = require('fs').createWriteStream 'extravagant-zombie.log'
# Use the helper function to start the app
app.start port: 3000, logfile: logfile
describe "GET '/'", ->
it "should have no blog if no one was registered", ->
zombie.visit 'http://localhost:3000', (err, browser, status) ->
expect(browser.text 'title').toEqual 'My Title'
asyncSpecDone()
asyncSpecWait()重点是:我所做的和我建议的是在启动服务器的模块中创建一个函数。然后,在任何需要的地方调用此函数。我不知道它是否是“好的设计”,但它是有效的,对我来说似乎是可读性和实用性。
此外,我怀疑在Node.js和CoffeScript中还没有“好的设计”。这些都是全新的,非常创新的技术。当然,我们可以“感觉到有些地方不对劲”--就像这种情况,两个不同的人不喜欢这个设计并改变了它。我们可以感觉到“错误的方式”,但这并不意味着已经有了“正确的方式”。总而言之,我相信我们将不得不在您的开发中发明一些“正确的方法”:)
(但也可以问一下做事情的好方法。也许有人有一个好主意,公众讨论将对其他开发人员有所帮助。)
https://stackoverflow.com/questions/7091875
复制相似问题