What steps should I take to configure a test environment specifically for conducting tests with selenium and phantomjs?

I am in the process of setting up my environment for headless testing using Selenium and PhantomJS.

Getting PhantomJS Ready:

To start, I created a folder named c:/phantomjs and downloaded all the necessary PhantomJS script files into it.

Next, I set up another folder called C:\xampp\htdocs\testPhantomJS.

After that, I installed nodeJS on my system.

Moving on, I navigated to the command prompt at C:\xampp\htdocs\testPhantomJS and proceeded to install PhantomJS with the following command:

C:\xampp\htdocs\testPhantomJS>npm install -g phantomjs

It's worth noting that the image attached shows a different location because it was taken from my colleague's computer. We are working on the same installation, which is why there is a discrepancy in the folder locations. Rest assured, the location I specified is where I completed the setup.

https://i.sstatic.net/kS0PQ.jpg

Now, when I type "phantomjs" in the command prompt, I get:

C:\xampp\htdocs\testPhantomJS>phantomjs

phantom>

Configuring Selenium-Webdriver

Similarly, I navigated to C:\xampp\htdocs\testPhantomJS in the command prompt and installed selenium webdriver with this command:

C:\xampp\htdocs\testPhantomJS>npm install selenium-webdriver

https://i.sstatic.net/UyZqs.png

Once the installation is complete, the folder structure looks like this: https://i.sstatic.net/ivJMl.png

Now, I have a test script named test.js, structured as follows:

describe('Test example.com', function(){
    before(function(done) {
        client.init().url('http://google.com', done);
    });

    describe('Check homepage', function(){
        it('should see the correct title', function(done) {
            client.getTitle(function(err, title){
                expect(title).to.have.string('Example Domain');
                done();
            });
        });

        it('should see the body', function(done) {
            client.getText('p', function(err, p){
                expect(p).to.have.string(
                    'for illustrative examples in documents.'
                );
                done();
            })
        });
    });

    after(function(done) {
        client.end();
        done();
    });
});

The challenge I'm facing now is figuring out where to place the above script and how to execute it. I don't just want to run it using PhantomJS; I also need to test it with both PhantomJS and Selenium.

Answer №1

Check out this awesome tutorial on setting up testing with selenium and phantomjs:

Let's put all the pieces together:

Merging Everything

First, make sure to run Selenium Server before running any tests:

1 java -jar selenium-server-standalone-2.28.0.jar Selenium will handle PhantomJS internally.

To connect to Selenium from JavaScript, use this code snippet:

// Create a Selenium Client using webdriverjs
var client = require('webdriverjs').remote({
    desiredCapabilities: {
        browserName: 'phantomjs'
    },
    logLevel: 'silent'
});

client.init();
Describe your tests and use the client variable to control the browser.

A detailed reference is available in the webdriverjs API documentation, but here's a brief example:

client.url('http://example.com/')
client.getTitle(function(title){
    console.log('Title is', title);
});
client.setValue('#field', 'value');
client.submitForm();
client.end();

Use Mocha and Chai syntax to write a test; checking properties of example.com:

describe('Test example.com', function(){
    before(function(done) {
        client.init().url('http://example.com', done);
    });

    describe('Check homepage', function(){
        it('should see the correct title', function(done) {
            client.getTitle(function(title){
                expect(title).to.have.string('Example Domain');
                done();
            });
        });

        it('should see the body', function(done) {
            client.getText('p', function(p){
                expect(title).to.have.string(
                    'for illustrative examples in documents.'
                );
                done();
            })
        });
    });

    after(function(done) {
        client.end();
        done();
    });
});

If you want to share one client initialization across multiple test files, create a Node module for it:

client.js:

exports.client = require('webdriverjs').remote({
    // Settings
};

test.js:

var client = require('./client').client;
var expect = require('chai').expect;
 
// Run tests

EDIT based on the question in the comments:

Here is how to install the selenium server, and yes you need to do it.

Selenium

Download Selenium Server as a single jar file and run it:

java -jar selenium-server-standalone-2.28.0.jar

Running the command starts a server for your testing code to connect to later. Remember to run Selenium Server each time you run tests.

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

Submit a form to the same page without reloading and toggle the visibility of a div after submission

Is there a way to submit a form without refreshing the page and hiding the current div while showing a hidden one? I attempted to use the following code, but it ends up submitting the form and reloading the page. <form method="post" name="searchfrm" a ...

Tips for implementing focusout on multiple elements while avoiding it when switching focus between them

Looking to create a searchable input that displays a dropdown of possible values on focusin, populated by server-side language. Attempted using focusin on elements not involved with the following code: $("body").not($(".dropdownSearch") ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

Unable to apply 100% height to flex child element

When it comes to creating a layout for my website, I have a simple idea in mind. I want the body content to take up at least 100% of the height of the page. This setup works perfectly on desktop screens, but when I switch to a mobile view (which changes th ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

Selenium Webdriver is causing login credentials to be considered incorrect, despite being accurate

Trying to automate testing for a login page on a website, encountering an issue where the program returns an error message stating that the username or password is incorrect even when the correct credentials are entered. Strangely, manually copying and p ...

What steps does VSCode take to ensure that all necessary node dependencies are installed for its extensions?

As I work on constructing my own pluggable application, I've been curious about how vscode handles its extensions' dependencies. Does it run npm install in each extension directory and utilize those installations individually? Or does it have a c ...

Unable to connect Dropzone to dynamically loaded DIV using AJAX

Using Dropzone for client-side image uploads has been a breeze. Take a look at this basic example that is currently up and running: If you examine the source code, you'll notice that I am utilizing JQuery to connect Dropzone to the upload1 div ID. H ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

How can I access the variable that evaluated as true in an if statement?

I'm facing a bit of a challenge with testing 2 variables for the same value. Is there a way to achieve this? var x = 'abc'; var y = 'def'; if (x=='abc' || y=='abc'){ z = 'result&a ...

Is there any npm module available that can generate user-friendly unique identifiers?

Struggling to come across a user-friendly and easily readable unique ID generator for storing orders in my backend system. I have considered using the timestamp method, but it seems too lengthy based on my research. ...

Adding my 'no' or 'id' in a URL using a JavaScript function can be accomplished by creating an onClick event

Here is the function I'm working on: function swipe2() { window.open('edit.php?no=','newwindow') } This is part of my PHP code (I skipped some lines): for ($i = $start; $i < $end; $i++) { if ($i == $total_results) { ...

Tips for enabling mouse functionality while utilizing PointerLockControls

I'm currently working on a 3D art gallery using Three.js and PointerLockControls for navigation. My goal is to have the artwork on the gallery walls clickable, triggering a pop-up window with additional information. However, it seems that PointerLock ...

Tips for utilizing the json_encode function with an array

I am trying to extract specific data from an object created using the json_encode function in PHP. while($locations=$req->fetch()){ $t = $locations->titre; $la = $locations->latitude; $lo = $locations->longitude; $typ = $lo ...

The JSONObject is returning an empty nested array

After retrieving a nested JSON array named "invested" from a JSON file, I encountered an issue where the array appeared to be empty when attempting to utilize it. The contents of my JSON file are as follows: { "invested": [ { &qu ...

Selenium successfully initializes a session with Chrome, only to abruptly crash moments later

Encountering errors when attempting to start a session. selenium.common.exceptions.SessionNotCreatedException: Message: session not created from chrome not reachable (Session info: chrome=80.0.3987.132) selenium.common.exceptions.SessionNotCreatedE ...

How can you calculate the ratio of one property value to another in AngularJS?

In my code, I am using ng-repeat to display data values from an object. <div ng-controller="myctrl"> <ul ng-repeat="number in numbers"> <li><span ng-bind="number.first"></span></li> <li><span ng-bind ...

Two out of the seven websites are experiencing issues with the same path URL in Webdriver Ruby

For logging out a user on the site, I have been using a method where I navigate to the same URL that is triggered when clicking the "logout" button. This approach was chosen as the logout button resides within a dropdown and it's simpler to trigger th ...

Ways to open Csv file located in another directory

When using @CsvFileSource, I encountered the error message "Classpath resource does not exist" when the file was placed in the data folder but worked fine when moved to the resources folder. What could be the issue with the file path? Below is the code sn ...