Javascript CasperJS在带有require或其他函数的循环中动态包含testfile

Javascript CasperJS在带有require或其他函数的循环中动态包含testfile,javascript,loops,casperjs,require,Javascript,Loops,Casperjs,Require,我有一个关于循环中扩展测试的问题。我有一个3级循环结构,其中我有URL、测试文件和视口大小,如下所示: var navigation = [ "http://www.url_1.com", "http://www.url_2.com", "http://www.url_3.com", "http://www.url_4.com" ]; var testfiles = [ "/componenttests/atoms/test_dropdown_buttons.js",

我有一个关于循环中扩展测试的问题。我有一个3级循环结构,其中我有URL测试文件视口大小,如下所示:

var navigation = [
  "http://www.url_1.com",
  "http://www.url_2.com",
  "http://www.url_3.com",
  "http://www.url_4.com"
];

var testfiles = [
  "/componenttests/atoms/test_dropdown_buttons.js",
  "/componenttests/atoms/test_conditional_buttons.js",
  "/componenttests/atoms/test_icon_buttons.js"
];


var viewPortsizes = [
  [1440, 900],
  [320, 480],
  [320, 568],
  [600, 1024],
  [1024, 768],
  [1280, 800]
];
现在我想根据以下策略来测试这一点:

对具有所有视口大小的所有URL运行所有测试

在以下结构中实施:

casper.start().then(function(){

  /* Loop through all URLs so that all are visited  */
  casper.eachThen(navigation, (function(response){

    var actUrl = response.data;

    /* Test different viewport resolutions for every URL */
    casper.eachThen(viewportSizes, function (responseView) {

      var actViewport = responseView.data;

      /* Set the viewport */
      casper.then(function () {            
        casper.viewport(actViewport[0], actViewport[1]);
      });

      /* Open the respective page and wait until its opened */
      casper.thenOpen(actUrl).waitForUrl(actUrl, function () {


        /* Single tests for every resolution and link */
        casper.each(testfiles, function (self, actTest, i) {

          /* AND HERE THE PROBLEM IS LOCATED, REQUIRE() ONLY WORKS ONCE */
          casper.then(function(){
            require('.' + testfiles[i]);
          });
        });
      });
    }));
})
.run(function() {
  this.test.done();
});
正如代码中所评论的,问题是我只能在需要时包含/加载这些测试文件一次

所以我在这里能做什么,我需要在最内部的循环中多次加载测试文件

测试文件只是像这样的片段

casper.then(function () {
  casper.waitForSelector(x("//a[normalize-space(text())='Bla']"),
    function success() {
      DO GOOD STUFF
    },
    function fail() {
      BAD THIGNS HAPPENED
    });
});
在第一次运行时,文件被包括在内,而在所有其他运行>1时,没有任何内容被包括在内,循环正常运行,但require不起作用

这肯定是必需的功能,因为当我将测试代码从文件直接复制到循环中时,它也工作了多次

我看到两种选择:

  • 将组件作为适当的模块编写,并在脚本或脚本的开头使用它们
  • 读取部件测试文件并评估它
适当模块 例如,您可以将测试组件定义为

exports.test = function(){
    casper.then(function () {
        ...
    });
};
然后,您可以在开始时要求他们:

testfiles = testfiles.map(function(path){
    return {
        path: path,
        test: require("." + path).test
    }
});
并直接在测试线束中使用:

casper.then(function(){
    testfiles[i].test();
});
每一轮都要评估 或者,您可以在测试线束中简单地使用它,而无需更改测试组件:

var fs = require("fs");
...
casper.then(function(){
    eval(fs.read("."+testfiles[i]));
});

感谢Artjom的快速响应,我现在将尽快进行测试。嗨,Artjom,两种解决方案都很好,感谢您的快速响应:)我直接选择了第二个选项并成功了。非常感谢。