javascript - 如何将对象传递给 Mocha 测试

标签 javascript node.js gruntjs mocha.js

我有一个自定义 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/

相关文章:

node.js - 在 Node.js 中创建一个空文件?

node.js - 向 glitch.me 服务器发出跨域请求

javascript - gruntjs - 从 javascript 访问 Rev(ed) 图像

javascript - 如何通过 grunt 运行 node.js 应用程序?

javascript - 如何使用 jQuery 同时在多个元素上更改不同的 css 属性

javascript - JavaScript/jQuery/AJAX 中的嵌套模板

javascript - 页脚下的空白

javascript - 在javascript中可以使用css3线夹吗?

node.js - linux (ubuntu) 上的 npm 安装错误

javascript - 使用 Grunt 和 Mocha 进行测试 : 'require' not found