【问题标题】:Full Integration Testing for NodeJS and the Client Side with Yeoman and Mocha使用 Yeoman 和 Mocha 对 NodeJS 和客户端进行全面集成测试
【发布时间】:2012-11-21 06:21:09
【问题描述】:

我使用 Yeoman 运行了很棒的客户端测试。 Yeoman 编译我的 CoffeeScript,在服务器中打开测试页面,使用 PhantomJS 访问它并将所有测试结果传递到命令行。这个过程非常 hacky,测试结果通过alert() 消息传递给 Phantom 进程,该进程创建一个临时文件并用 JSON 格式的消息填充它。 Yeoman(好吧,Grunt)遍历临时文件,解析测试并将它们显示在命令行中。

我解释这个过程的原因是我想给它添加一些东西。我也进行了服务器端测试。他们使用 mocha 和 supertest 来检查 API 端点和 Redis 客户端以确保数据库状态符合预期。但我想合并这两个测试套件!

我不想为服务器调用编写客户端模拟响应。我不想发送服务器模拟数据。在此过程中,我将更改服务器或客户端,并且测试不会失败。我想做一个真正的集成测试。因此,每当测试在客户端完成时,我想要一个钩子在服务器端运行相关测试(检查数据库状态、会话状态、移动到不同的测试页面)。

有什么解决办法吗?或者,或者,我从哪里开始对 Yeoman / Grunt / grunt-mocha 进行 hack 以使其工作?

我认为 grunt-mocha 中的 Phantom Handlers 是一个不错的起点:

// 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')
  };

谢谢!会有赏金的。

【问题讨论】:

    标签: javascript unit-testing node.js coffeescript gruntjs


    【解决方案1】:

    我不知道 Yeoman - 我还没有尝试过 - 但我已经解决了剩下的难题。我相信你会弄清楚其余的。

    为什么要进行集成测试?

    在您的问题中,您谈论的是同时使用模拟运行客户端测试和服务器端测试的情况。我假设由于某种原因,您无法让两个测试集都使用相同的模拟运行。否则,如果您在客户端更改了模拟,您的服务器端测试将失败,因为它们会获取损坏的模拟数据。

    您需要的是集成测试,因此当您在无头浏览器中运行一些客户端代码时,您的服务器端代码也会运行。此外,仅仅运行你的服务器端和客户端代码是不够的,你还希望能够在两边都放置断言,不是吗?

    Node 和 PhantomJS 的集成测试

    我在网上找到的大多数集成测试示例都使用SeleniumZombie.js。前者是一个基于 Java 的大型框架,用于驱动真正的浏览器,而后者是一个简单的 jsdom 包装器。我假设您对使用其中任何一个都犹豫不决,并且更喜欢PhantomJS。当然,棘手的部分是从你的 Node 应用程序中运行它。我就是这样。

    有两个node模块来驱动PhantomJS:

    1. phantom
    2. node-phantom

    不幸的是,这两个项目似乎都被他们的作者抛弃了,其他社区成员分叉了他们并适应了他们的需求。这意味着这两个项目都被分叉了很多次,而且所有的分叉都几乎没有运行。 API 几乎不存在。我用one of the phantom forks 运行了我的测试(谢谢Seb Vincent)。这是一个简单的应用程序:

    '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 运行您的测试:mocha -t 2s 您可能需要增加默认超时设置才能运行更高级的测试。

    所以,正如您所见,整个事情都是可行的。 Here's the repo with complete example.

    【讨论】:

    • 嘿,谢谢! (1) 我更喜欢 PhantomJS,因为 Selenium 和 ZombieJS 都很慢 (2) 虽然APP 非常适合测试,但节点服务器会因内存泄漏而在生产中崩溃。 (3) 添加变量以便测试您的代码也是不好的做法。 (4) 看起来很棒。正如预期的那样,它有很多问题,笨拙,缓慢且需要大量工作。 'doable' 确实是关键字 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    相关资源
    最近更新 更多