我有一个自定义 Node 服务器并将其作为对象传递给一些测试。这是我的 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']
}
}
});
如何在测试中使用我在 Gruntfile 中创建的变量?还有其他方法可以将内容传递给我的测试吗?
最佳答案
来自 Mocha 文档:
--globals
Accepts a comma-delimited list of accepted global variable names. For example, suppose your app deliberately exposes a global named app and YUI, you may want to add --globals app,YUI. It also accepts wildcards. You could do --globals 'bar' and it would match foobar, barbar, etc. You can also simply pass in '' to ignore all globals.
简而言之,全局选项用于告诉 mocha 忽略某些全局变量,而不是在测试中公开这些变量。
如果您想使用 mocha 测试模块,您应该在测试(或测试助手)中require
它。
类似 supertest 的框架将包装一个 HTTPServer 并允许您很好地测试端点。我创建了一个简短的 example这展示了如何使用 supertest 和 mocha 来测试简单的 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);
});
});
关于javascript - 如何将对象传递给 Mocha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699453/