Cam*_*mel 25 javascript unit-testing node.js coffeescript gruntjs
我和Yeoman一起运行了很棒的客户端测试.Yeoman编译我的CoffeeScript,在服务器中打开测试页面,使用PhantomJS访问它并将所有测试结果传递给命令行.这个过程非常糟糕,测试结果通过alert()消息传递给Phantom进程,该进程创建一个临时文件,并将消息填充为JSON.Yeoman(好吧,Grunt)遍历临时文件,解析测试并在命令行中显示它们.
我解释这个过程的原因是我想为它添加一些东西.我也得到了服务器端测试.他们使用mocha和supertest来检查API端点和Redis客户端,以确保数据库状态符合预期.但我想合并这两个测试套件!
我不想为服务器调用编写客户端模拟响应.我不想发送服务器模拟数据.在某个地方,我将更改服务器或客户端,测试不会失败.我想做一个真正的集成测试.所以,当在客户端的测试结束我想钩上运行服务器端的相关测试(检查数据库状态,会话状态,移动到不同的测试页).
这有什么解决方案吗?或者,或者,我在哪里开始攻击Yeoman/Grunt/grunt-mocha来完成这项工作?
我认为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')
  };
谢谢!这将是一个赏金.
And*_*кин 24
关于Yeoman,我不知道- 我还没有尝试过 - 但我还有其他的谜题.我相信你会弄明白其余的.
在您的问题中,当您同时进行客户端测试和使用模拟运行的服务器端测试时,您谈论的是这种情况.我认为由于某种原因,你不能让两个测试集运行相同的模拟.否则,如果您在客户端更改了模拟,则服务器端测试将失败,因为它们将获取损坏的模拟数据.
您需要的是集成测试,因此当您在无头浏览器中运行某些客户端代码时,您的服务器端代码也会运行.而且,仅仅运行服务器端和客户端代码是不够的,你还希望能够在双方都设置断言,不是吗?
我在网上找到的大多数集成测试的例子都使用Selenium或Zombie.js.前者是一个基于Java的大型框架来驱动真正的浏览器,而后者是一个简单的jsdom包装器.我假设您对使用其中任何一种都犹豫不决,并且更喜欢PhantomJS.当然,棘手的部分是从您的Node应用程序运行.我得到了那个.
有两个节点模块可以驱动PhantomJS:
不幸的是,这两个项目似乎被他们的作者和其他社区成员放弃了,并且适应了他们的需求.这意味着两个项目都分叉了很多次,所有的叉子几乎都没有运行.API几乎不存在.我让我的测试运行了一个幻影叉(谢谢你,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您可能需要增加默认超时设置才能运行更多的演进测试.
所以,你可以看到整个事情是可行的. 这是带有完整示例的回购.
| 归档时间: | 
 | 
| 查看次数: | 11129 次 | 
| 最近记录: |