在“集成”testing中了解摩卡语法

我有一个相当广泛的背景与Ruby和Rspec。 然而,当我学习Node和Mocha时,我遇到了一些我似乎无法理解的语法。

以本教程为例,testing路由包含以下内容(使用CoffeeScript)。 还应该指出,我已经看到了很多其他的地方向摩卡解释初学者的例子。

require "should" routes = require "../routes/index" describe "routes", -> describe "index", -> it "should display index with posts", -> req = null res = render: (view, vars) -> view.should.equal 'index' vars.title.should.equal('My Coffeepress Blog') routes.index(req, res) 

如果我理解正确,这个testing设置模拟请求和响应variables(分别为req和res),并将它们发送到routes.index()函数。

但是, 我不明白的是,为什么以及如何在render()函数调用中进行断言。 这似乎是一个完全不同的testing方法,因为我习惯于设置数据,testing数据与预期值,并将数据撕掉。 在这里,似乎“build立数据”(创build一个模拟的res对象)的一部分正在作出断言。

任何人都可以解释这一点与Rspecstream利的人?

render函数正在调用,我假设,在您的index路线。 它可能看起来像这样:

 index: (req, res, next) -> res.render 'index', { title: 'My Coffeepress Blog'} 

您正在传递一个存根响应,暴露render方法,以便您可以拦截该调用并声明调用; 即第一个参数( view参数)和数据( vars对象)。 这是所有这些都是必需的,因为超越这一点当然会testing底层框架。

对callback进行断言通常会导致类似于“颠倒”的查找testing,因为代码不会读取top => down。 尽pipe如此,这是asynchronous/callback世界中的生活。

如果它很烦人,你可以捕获一个局部variables的调用,并在事后作出断言,但是一旦你编写了一段时间的callback,这开始是不必要的冗长:

 # snip viewName = null locals = null res: render: (view, vars) > viewName = view locals = vars routes.index (req, res) viewName.should.equal 'index' locals.title.should.equal 'My Coffeepress Blog' 

这有帮助吗?