node.js - 使用 Mocha 测试 Express : a promise-based test will not run by itself?

标签 node.js express promise mocha.js

我有两个测试文件。当仅存在 test1.js 时,不会运行任何测试,并且 mocha 会报告“0 通过”测试。当 test1.js 和 test2.js 存在但都依赖于 promise 时,仍然没有测试运行,并且 mocha 仍然报告“0 通过”。但是,当其中一个测试被修改为不使用 promise 时,mocha 会运行这两个测试并且它们会成功。有没有搞错?这是我的文件:

index.js:

require('./server').then( function(server) {
  server.listen(8080, function() {
  console.log("Started server");
  });
);

服务器.js:

var express = require('express');
var server = express();

module.exports = new Promise((function(resolve, reject) {
  return resolve(server);
}));

test1.spec.js:

require('./server').then(function(server) {
  describe('Test Suite #1', function () {
    it('should run test #1', function testSomething(done) {
      return done();
    });
  });
});

test2.spec.js(server.js 用作 promise ,测试运行):

require('./server').then(function(server) {
  describe('Test Suite #2', function () {
    it('should run test #2', function testSomethingElse(done) {
      return done();
    });
  });
});

test2.spec.js(server.js用作 promise ,两个测试都运行):

var server = require('./server');
describe('Test Suite #2', function () {
  it('should run test #2', function testSomethingElse(done) {
    return done();
  });
});

要运行它们,我只需安装并运行 Nodejs、express 和 mocha:

% mocha "*.spec.*"

我知道我在这些示例中没有使用服务器变量,但当然真正的测试需要返回一个 promise ,因为有时 server.js 正在访问远程系统以获取配置数据。我可以解决这个问题,但是任何帮助理解这里发生的事情的帮助都将不胜感激!

最佳答案

您需要同步描述和定义所有测试。否则 Mocha 无法识别它们。如果您需要进行一些异步设置,请使用 before 或 beforeEach 函数:

describe('Test Suite #1', function () {
  var server;
  before(function(done){
    require('./server').then(aServer => {
      server = aServer;
      done();
    });
  });
  it('should run test #1', function testSomething(done) {
    return done();
  });
});

关于node.js - 使用 Mocha 测试 Express : a promise-based test will not run by itself?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39294187/

相关文章:

node.js - "Everything is middleware"

node.js - "message failed to fetch from registry"尝试安装任何模块时

javascript - 电子邮件未从 heroku Nodejs 应用程序发送(本地工作正常)

javascript - Passport js通过url验证

javascript - 第二个 .then() on promise 被调用时数据未定义

angularjs - 如何在 AngularJS 中取消 $http 请求?

node.js - nodejs 配置模块乐观主义者还是 nconf?

javascript - 如何使用 node-mongodb-native 连接到 Modulus.io?

javascript - Express js路由错误("Cannot GET/")

javascript - 如何循环遍历 Firebase 文档以查找匹配文档,然后提取名称?