How to dynamically include a test file in CasperJS using a loop and the require function

A question has come up regarding extended testing within loops. The scenario involves a 3-level loop structure, incorporating URLs, Testfiles, and Viewportsizes as displayed below:

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]
];

The objective is to execute the following strategy:

Run all TESTS on ALL URLs with ALL VIEWPORT SIZES

This will be implemented in the following structure:

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) {

          /* THE ISSUE LIES HERE - REQUIRE() ONLY WORKS ONCE */
          casper.then(function(){
            require('.' + testfiles[i]);
          });
        });
      });
    }));
})
.run(function() {
  this.test.done();
});

As indicated in the code, there is a limitation where the testfiles can only be included/loaded once using require.

So, the challenge remains: how can these testfiles be loaded multiple times within the inner loop?

The testfiles consist of snippets such as

casper.then(function () {
  casper.waitForSelector(x("//a[normalize-space(text())='Bla']"),
    function success() {
      DO GOOD STUFF
    },
    function fail() {
      BAD THINGS HAPPENED
    });
});

Currently, the file is included in the first run, but subsequent runs beyond 1 do not include it. Although the loops operate correctly, the require functionality does not persist.

It is evident that the issue lies with the require functionality because copying the test code directly into the loop allows it to work multiple times.

Answer №1

There are two possible approaches:

  • Develop your components as modules and import them at the start of your script or
  • review the component test file and execute it using eval.

Modular Approach

You can define your test components like this:

exports.test = function(){
    casper.then(function () {
        ...
    });
};

Then, you can import them at the beginning:

testfiles = testfiles.map(function(path){
    return {
        path: path,
        test: require("." + path).test
    }
});

and directly utilize them in the test environment:

casper.then(function(){
    testfiles[i].test();
});

Dynamic Evaluation

Alternatively, you can apply this method in your testing setup without altering your test components:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve documents from a nearby directory using an online platform

I have a gridview in an aspx page that needs to display all the xml files from a folder on the client machine. Is there a way to retrieve the contents of a folder using the directory path? I currently have code that works when running it locally, but I am ...

"Customize your search experience with a bootstrap search bar featuring multiple input fields

Currently working on a website using Bootstrap and trying to create a filter bar for the items displayed on the page. I am looking to include one or more input fields (highlighted in red) and one or more dropdowns (highlighted in blue). The width of the ba ...

Problem with the operation of SetInterval/ClearInterval loop

While I am aware that this question has been addressed previously, none of the solutions provided seemed to resolve my specific issue. The problem lies within my timer function which, upon invocation, is supposed to utilize setInterval to run every second ...

Stopping the webdriver in Node.js gracefully without crashing it can be achieved through a

Can the selenium webdriver be halted without terminating node? I've encountered a problem attempting to create an API tool that conducts web automation upon receiving a get request. Essentially, I am executing the selenium webdriver on a get request ...

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

Using HTML and JavaScript allows for the video URL to seamlessly open in the default video player app on the device

Working on my mediaplayer website, I want to give users the option to choose which app to play their uploaded videos with. So far, I've attempted to implement a button that triggers this action: window.open("video.mkv", '_blank'); Howeve ...

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

What is the best way to pass a form result from a parent component to a child component

In the setup, there is a child component containing a form with various options for selection. The goal is to capture the user's selection and process it within this child component. Despite attempting to utilize an event in the parent component, the ...

Using Javascript to fetch JSON data from a PHP file hosted on an IIS server, incorporating JSONP with

I have set up an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). The structure of the root directory is as follows: index.html, src/index.js, src/send_payment.php Currently, I am attempting to retrieve a basi ...

The rationale behind organizing analogous variables into groups

Currently, I am grappling with determining the optimal logic for grouping parameters within a specified tolerance level. Let me illustrate this with an example... Task1: parameter1=140 Task2: parameter1=137 Task3: parameter1=142 Task4: parameter1=139 Task ...

Using ReactJS and Ruby on Rails to implement an AJAX delete request

There is a component named Items residing inside a parent component called ItemsContainer. A click on a button within the Items component triggers an Ajax function to delete that specific Item. However, I am encountering a 500 error message at the moment ...

Obtain JSON information using an underscore template

As someone fairly new to using Backbone and Underscore, and web development in general, I am seeking guidance on how to retrieve individual model data on-click from a template format in order to populate a pop-up modal. Any advice or direction would be gre ...

php failure to execute included file

Hey there! I'm currently facing an issue with including a file that contains all of my 'head' information. My goal is to simplify and streamline my page by breaking it down. In my index.php file, here's what I did: <?php include & ...

What is the best way to update text in an element when hovering or activating it?

I am currently designing a website with a prominently placed "Hire me" button in the center of the page. The button was implemented using the following code: <div id="hire_me_button"> <a href="contact.html"><h4 id="hire_me" class="butto ...

Creating dynamic form fields in Ionic 2#UniqueContent

Is it possible to dynamically add input fields? Does anyone have an example of how to do this? For instance, if I select 2 from my options, I want to see 2 input fields. If I select 5, then show me 5 input fields. This is what I've been thinking: &l ...

Retrieving a string during an update request within the KendoUI datasource

I am facing an issue with my grid and data source setup. The schema.parse function is causing some unexpected behavior. Whenever I try to update or create a new row, the schema.parse() function is called again. The parameter passed to it is a string conta ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...