如何将对象传递给Mochatesting

我有一个自定义的节点服务器,并将其作为对象传递给一些testing。 这是我的Gruntfile:

module.exports = function(grunt) { // Add the grunt-mocha-test tasks. grunt.loadTasks('node_modules/grunt-mocha-test/tasks'); grunt.initConfig({ // Configure a mochaTest task pkg: grunt.file.readJSON('package.json'), mochaTest: { test: { options: { reporter: 'spec', globals : 'MyServer' }, src: ['./server/test/custom/*.js'] } } }); 

如何在我的testing中使用我在Gruntfile中创build的variables? 还有另一种方式来传递东西到我的testing?

从摩卡文档:

–globals

接受逗号分隔的接受的全局variables名称列表。 例如,假设您的应用程序故意公开全局命名应用程序和YUI,您可能需要添加 – 全局应用程序YUI。 它也接受通配符。 你可以做 – 全球“ 酒吧”,它会匹配foobar,barbar等。你也可以简单地通过“ '来忽略所有的全局variables。

简而言之,globals选项用于告诉摩卡忽略某些全局variables,而不是在testing中公开这些variables。

如果你想用摩卡testing一个模块,你只require在你的testing(或testing助手)中进行testing。

像supertest这样的框架将包装一个HTTPServer,并允许你很好地testing端点。 我创build了一个简短的例子 ,展示了如何使用supertest和mocha来testing一个简单的HTTPServer应用程序。 相关代码如下:

 // index.js var http = require('http'); module.exports = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }); 
 // server-test.js var server = require('./index.js'); var supertest = require('supertest'); var app = supertest(app); describe('server', function () { it('responds with a welcoming message', function (done) { app.get('/') .expect(200, /Hello World/, done); }); });