完全集成的测试和的NodeJS与约曼和摩卡客户端(Full Integration Testing

2019-08-03 12:06发布

我得到了我约曼运行真棒客户端测试。 约曼编译我的CoffeeScript,在服务器开启了测试页面,用PhantomJS参观,并通过所有测试结果的命令行。 该过程是相当哈克,测试结果经由传递alert()消息,其创建一个临时文件,并与邮件作为JSON填充它的幻影的过程。 约曼(当然,咕噜)循环通过临时文件,解析所述测试并将它们显示在命令行。

我解释了处理的原因,我想了一些东西添加到它。 我得到了服务器端的测试以及。 他们用摩卡和supertest检查API端点和Redis的客户端,以确保数据库状态正常。 但我想合并这两个测试套件!

我不想写的服务器调用客户端模拟响应。 我不想向服务器发送模拟数据。 沿途某处,我会改变服务器或客户端和测试将不会失败。 我想做一个真正的集成测试。 所以,当在客户端的测试结束我想钩上运行服务器端的相关测试(检查数据库状态,会话状态,移动到不同的测试页)。

是否有此解决方案的任何? 或者,altenatively,我从哪里开始黑客攻击约曼/格朗特/咕噜,摩卡,使这项工作?

我想,幻影处理程序中的咕噜,摩卡是一个良好的开端:

// Handle methods passed from PhantomJS, including Mocha hooks.
  var phantomHandlers = {
    // Mocha hooks.
    suiteStart: function(name) {
      unfinished[name] = true;
      currentModule = name;
    },
    suiteDone: function(name, failed, passed, total) {
      delete unfinished[name];
    },
    testStart: function(name) {
      currentTest = (currentModule ? currentModule + ' - ' : '') + name;
      verbose.write(currentTest + '...');
    },
    testFail: function(name, result) {
        result.testName = currentTest;
        failedAssertions.push(result);
    },
    testDone: function(title, state) {
      // Log errors if necessary, otherwise success.
      if (state == 'failed') {
        // list assertions
        if (option('verbose')) {
          log.error();
          logFailedAssertions();
        } else {
          log.write('F'.red);
        }
      } else {
        verbose.ok().or.write('.');
      }
    },
    done: function(failed, passed, total, duration) {
      var nDuration = parseFloat(duration) || 0;
      status.failed += failed;
      status.passed += passed;
      status.total += total;
      status.duration += Math.round(nDuration*100)/100;
      // Print assertion errors here, if verbose mode is disabled.
      if (!option('verbose')) {
        if (failed > 0) {
          log.writeln();
          logFailedAssertions();
        } else {
          log.ok();
        }
      }
    },
    // Error handlers.
    done_fail: function(url) {
      verbose.write('Running PhantomJS...').or.write('...');
      log.error();
      grunt.warn('PhantomJS unable to load "' + url + '" URI.', 90);
    },
    done_timeout: function() {
      log.writeln();
      grunt.warn('PhantomJS timed out, possibly due to a missing Mocha run() call.', 90);
    },

    // console.log pass-through.
    // console: console.log.bind(console),
    // Debugging messages.
    debug: log.debug.bind(log, 'phantomjs')
  };

谢谢! 会有这个赏金。

Answer 1:

我不知道约曼 -我还没有尝试过-但我得到了这一难题运行的其余部分。 我相信你会找出休息。

为什么做集成测试?

在你的问题你在谈论的情况,当你有两个客户端测试,并与嘲笑运行服务器端的测试。 我认为由于某种原因,你不能用相同的嘲笑运行这两个测试集。 否则,如果你改变了对客户端的嘲笑你的服务器端测试将失败,因为他们将获得破模拟数据。

你需要的是集成测试,所以当你在无头的浏览器中运行一些客户端代码服务器端代码也将运行。 此外,只需运行服务器端和客户端代码是不够的,你也希望能够把断言两侧,不是吗?

集成测试与节点和PhantomJS

大部分的集成测试,我发现无论是在网上使用的例子硒或Zombie.js 。 前者是一个很大的基于Java的框架,以推动真正的浏览器,而后者是围绕一个简单的包装jsdom 。 我假设你犹豫不决,请使用那些并希望PhantomJS 。 最棘手的部分,当然是让从您的节点应用程序运行。 而我得到了这一点。

有两个节点模块驱动PhantomJS:

  1. 幻影
  2. 节点幻象

不幸的是,这两个项目似乎对他们的作者放弃了和其他社区成员叉他们,适应他们的需求。 这意味着,这两个项目得到了分叉无数次和所有叉勉强运行。 API是几乎不存在。 我得到了我的测试与运行幻象叉的一个 (谢谢你, 勒布文森特 )。 这里有一个简单的应用程序:

'use strict';
var express = require('express');

var app = express();

app.APP = {}; // we'll use it to check the state of the server in our tests

app.configure(function () {
    app.use(express.static(__dirname + '/public'));
});

app.get('/user/:name', function (req, res) {
    var data = app.APP.data = {
        name: req.params.name,
        secret: req.query.secret
    };
    res.send(data);
});

module.exports = app;

    app.listen(3000);
})();

它侦听请求/user ,并返回路径参数name和查询参数secret 。 这里就是我所说的服务器的页面:

window.APP = {};

(function () {
    'use strict';

    var name = 'Alex', secret ='Secret';
    var xhr = new XMLHttpRequest();
    xhr.open('get', '/user/' + name + '?secret=' + secret);
    xhr.onload = function (e) {
        APP.result = JSON.parse(xhr.responseText);
    };
    xhr.send();
})();

下面是一个简单的测试:

describe('Simple user lookup', function () {
    'use strict';

    var browser, server;

    before(function (done) {
        // get our browser and server up and running
        phantom.create(function (ph) {
            ph.createPage(function (tab) {
                browser = tab;
                server = require('../app');
                server.listen(3000, function () {
                    done();
                });
            });
        });
    });

    it('should return data back', function (done) {
        browser.open('http://localhost:3000/app.html', function (status) {

            setTimeout(function () {
                browser.evaluate(function inBrowser() {
                    // this will be executed on a client-side
                    return window.APP.result;
                }, function fromBrowser(result) {
                    // server-side asserts
                    expect(server.APP.data.name).to.equal('Alex');
                    expect(server.APP.data.secret).to.equal('Secret');
                    // client-side asserts
                    expect(result.name).to.equal('Alex');
                    expect(result.secret).to.equal('Secret');
                    done();
                });
            }, 1000); // give time for xhr to run

        });
    });
});

正如你可以看到我有轮询超时内部服务器。 这是因为所有的幻影绑定是不完整的,太受限制。 正如你可以看到我能够在一个单一的测试,以检查这两个客户端状态和服务器状态。

与运行测试摩卡 : mocha -t 2s你可能需要增加默认超时设置更进化的测试运行。

所以,你可以看到整个事情是可行的。 下面是与完整的示例来回购。



文章来源: Full Integration Testing for NodeJS and the Client Side with Yeoman and Mocha