我不知道Yeoman- 我还没有尝试过 - 但我已经完成了剩下的拼图。我相信你会弄清楚剩下的事情。
为什么要进行集成测试?
在您的问题中,您谈论的是当您同时使用模拟运行客户端测试和服务器端测试时的情况。我认为由于某种原因,您无法使用相同的模拟运行两个测试集。否则,如果您更改客户端上的模拟,您的服务器端测试将失败,因为它们会获取损坏的模拟数据。
您需要的是集成测试,因此当您在无头浏览器中运行一些客户端代码时,您的服务器端代码也会运行。此外,仅仅运行服务器端和客户端代码是不够的,您还希望能够在两侧都添加断言,不是吗?
Node 和 PhantomJS 的集成测试
我在网上找到的大多数集成测试示例都使用Selenium http://seleniumhq.org/ or 僵尸.js http://zombie.labnotes.org/。前者是一个基于 Java 的大型框架,用于驱动真正的浏览器,而后者是一个简单的包装器jsdom https://github.com/tmpvar/jsdom。我假设您对使用其中任何一个都犹豫不决,并且更喜欢PhantomJS http://phantomjs.org/。当然,棘手的部分是从 Node 应用程序中运行它。我明白了。
有两个节点模块来驱动 PhantomJS:
- phantom https://npmjs.org/package/phantom
- 节点幻象 https://npmjs.org/package/node-phantom
不幸的是,这两个项目似乎都被其作者放弃了,其他社区成员对它们进行了分叉并适应了他们的需求。这意味着这两个项目都被分叉了很多次,而且所有分叉都几乎没有运行。 API 几乎不存在。我的测试运行了幻叉之一 https://github.com/sebv/phantomjs-node(谢谢你,塞布·文森特 https://github.com/sebv)。这是一个简单的应用程序:
'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 http://visionmedia.github.com/mocha/: mocha -t 2s
您可能需要增加默认超时设置才能运行更先进的测试。
所以,正如你所看到的,整个事情是可行的。 这是带有完整示例的存储库。 https://github.com/listochkin/node-phantom-test-example