testing - 从 vows 启动服务器进行测试的正确方法是什么?

标签 testing node.js coffeescript express vows

我有一个 express 服务器,我正在使用 vows 进行测试。我想从 vows 测试套件中运行服务器,这样我就不需要让它在后台运行以使测试套件工作,然后我可以创建一个运行服务器并对其进行测试的蛋糕任务隔离。

server.coffee 我创建了(express)服务器,配置它,设置路由并调用 app.listen(port),如下所示:

# 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) 在功能上与誓言文档中的相似...

当我在上述测试中 require 服务器时,它会自动开始运行服务器并且测试运行并通过,这很好,但我不觉得我这样做是“正确”的方式.

我无法控制服务器何时启动,如果我想将服务器配置为指向“测试”环境而不是默认环境,或者更改我测试时的默认日志记录级别,会发生什么?

PS 我要将我的誓言转换为 Coffeescript,但现在它全部在 js 中,因为我处于从文档中学习的模式!

最佳答案

这是一个有趣的问题,因为昨晚我做了你想做的事。我有一个小的 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 中还没有“好的设计”。这些是全新的、非常创新的技术。当然,我们可以“感觉有问题”——比如这种情况,两个不同的人不喜欢设计并改变了它。我们可以感觉到“错误的方式”,但这并不意味着已经有“正确的方式”。总而言之,我相信我们将不得不在您的开发中发明一些“正确的方法”:)

(但也可以询问做事的好方法。也许有人有一个好主意,公开讨论会对其他开发人员有所帮助。)

关于testing - 从 vows 启动服务器进行测试的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7091875/

相关文章:

testing - RSpec 和 Factory Girl - 建立独特的联系?

ios - Swift - 使用 XCTest 测试包含闭包的函数

c++ - 测试串口应用

javascript - 如何使用groupby方法在sequelize postgres中获取特定id的表特定数据

node.js - PugJs - 找不到模板文件/忽略目录

testing - 如何测试包含 log.Fatal() 的 Go 函数

javascript - Sequelize 如何正确创建具有约束的用户数据?

Coffeescript 类和范围以及粗细箭头

coffeescript - 在 coffeescript 中, "is not"和 "!="有什么区别?

javascript - 使用 CoffeeScript 运行 JQuery