javascript - 如何确保在 Node 上使用 mocha 和 phantomjs 进行的每个测试都未触及 HTML

标签 javascript node.js testing phantomjs mocha.js

我写了一个网络应用程序,我想在其中使用 mocha 和 phantomjs 从命令行进行一些 DOM 测试,我正试图找出最好的方法来做到这一点。

由于 web 应用程序正在执行大量 DOM 操作,我希望能够为每个测试加载全新的 DOM。我尝试使用 webpage module of phantomjs但我不知道如何在页面上运行 mocha 测试(或者这是否是正确的方法)。

当然,我可以只创建一个文件 test.html,我通过脚本标签在其中包含 mocha,然后运行 ​​phantomjs test.html。但是我怎样才能确保 DOM 在每次测试中都没有受到影响呢?为每个具有相同内容的测试添加一个 HTML 文件将是一场噩梦。

我目前拥有的:

我的 testrunner.js:

var Mocha = require('mocha'),
    expect = require('expect.js'),
    fs    = require('fs'),
    path  = require('path');

var mocha = new Mocha(
{
  ui: 'bdd'
});
// I only add one file for now
mocha.addFile(
  path.join(__dirname, 'tests_integration/test.js')
);

mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

我的测试.js: 这是我挣扎的地方,因为我不知道如何在页面内运行测试:

var phantom = require('phantom');
phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open("http://test.local", function (status) {
      page.evaluate(function (tests) {
        // here I need to run my tests, which obviously doesnt work that way
        describe('DOM tests',function(){
          it('should be able to acces the page',function(){
            expect(document.body).not.to.be(undefined)
          });
        });
        return document.body
      }.bind(tests), function (html) {
        ph.exit();
      });
    });
  });
});

为了运行测试,我执行了 node integration-runner.js。我想到的一种解决方案是使用 includeJS将 mocha 注入(inject)幻影页面,但这对我来说似乎有点老套。

我做的完全错了吗?

最佳答案

好的,经过一些研究并与其他开发人员交谈后,创建不同的 HTML 文件似乎是最干净的解决方案。但是,由于我不想在更改我的 web 应用程序时手动更新所有这些文件,因此我决定使用 injectJS 解决方案 as described in this great post .

现在我可以动态地将 mocha 测试文件注入(inject)实时站点并运行它们。

关于javascript - 如何确保在 Node 上使用 mocha 和 phantomjs 进行的每个测试都未触及 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897176/

相关文章:

javascript - Jquery 可排序不适用于触摸

javascript - 为什么我不能用 Mongoose 设置数据库?

java - 我应该使用生产代码中的 DAO 来设置和验证测试吗?

node.js - 根据请求参数 express 有条件地使用中间件

Node.js redis 订阅内存泄漏

javascript - 如何通过浏览器(Chrome)在运行时引发 javascript 错误?

python - 测试 Django REST View 集的 POST 方法

javascript - 如何使用 JSON API?

javascript - 为什么 Google Chrome 控制台在输入时会抛出 "SyntaxError: Unexpected token }"(

javascript - 如何将 arraylist 转换为 Javascript 中的字符串?