End-to-end Testing with WebdriverJS, Selenium, and Jasmine

After trying multiple examples with slight variations in the code, I am still unable to get it to work as expected. The code below consists of commented sections that claim to work but do not in my case.

The tools I am using include: - selenium-webdriver - jasmine-node-reporter-fix (to resolve jasmine-node errors)

This involves a simple asynchronous test where Google is opened and searched, followed by retrieving the page title.

Issue; The page title returned is from the Google homepage rather than the search results page, even though the browser ends up on the search results page.

Code

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.firefox()).
    build();

jasmine.DEFAULT_TIMEOUT_INTERVAL = 9999999;

describe('basic test', function () {

    it('should be on correct page', function (done) {
        //driver.get('http://www.wingify.com');
        //driver.getTitle().then(function (title) {
        //  expect(title).toBe('Wingify');
        //  // Jasmine waits for the done callback to be called before proceeding to next specification.
        //  done();
        //});


        driver.get("http://www.google.com");
        driver.findElement(webdriver.By.name("q")).sendKeys("webdriver");
        driver.findElement(webdriver.By.name("btnG")).click();
        //driver.getTitle().then(function (title) {
        //  console.log(title);
        //  console.log(expect);
        //  expect(title).toBe('webdriver - Google Search');
        //  done();
        //});
        driver.wait(function () {
            driver.getTitle().then(function (title) {
                expect(title).toBe('webdriver - Google Search');
                done();
            });
        }, 5000);

    });
});

Result

Failures:

  1) basic test should be on correct page
   Message:
     Expected 'Google' to be 'webdriver - Google Search'.
   Stacktrace:
     Error: Expected 'Google' to be 'webdriver - Google Search'.
    at C:\Stash\Will-Hancock\grunt-jasmine\spec\test-spec.js:31:19
    at C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\goog\base.js:1243:15
    at webdriver.promise.ControlFlow.runInNewFrame_ (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:1539
:20)
    at notify (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:362:12)
    at notifyAll (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:331:7)
    at resolve (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:309:7)
    at fulfill (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:429:5)
    at Object.webdriver.promise.asap (C:\Stash\Will-Hancock\grunt-jasmine\node_modules\selenium-webdriver\lib\webdriver\promise.js:671:5)

Finished in 4.281 seconds
1 test, 1 assertion, 1 failure, 0 skipped

Despite suggestions to extend the jasmine timeout or utilize the Jasmine done() method, the issue persists.

I am puzzled about why the wait function does not delay as expected. Results are generated instantly regardless of the provided timeout value.

Answer №1

Check out this helpful response - "The internal function will generate a promise that driver.wait will be waiting for and will consider its boolean value as the waiting condition"

The recommended modification is -

driver.wait(function () {
            return driver.getTitle().then(function (title) {
                return title === 'Selenium - Google Search';
            });
        }, 5000);

Answer №2

Having faced an issue, the previous approach did not allow Jasmine to wait for the page to load before asserting using driver.wait.

Jasmine would complete before driver.wait was able to return.

To address this, I opted to utilize Jasmine's waitsFor() method instead.

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

describe('basic test', function () {

    it('should navigate to correct page', function () {
        var expectedTitle = 'webdriver - Google Search',
            pageTitle = '';

        driver.get("http://www.google.com");
        driver.findElement(webdriver.By.name("q")).sendKeys("webdriver");
        driver.findElement(webdriver.By.name("btnG")).click();

        // wait for the page title to ensure navigation is complete
        waitsFor(function () {
            driver.getTitle().then(function (_pageTitle) {
                pageTitle = _pageTitle;
            });
            return pageTitle === expectedTitle;
        }, 'Checking page title for successful navigation', 6000);

        // check if the title matches the expected value
        runs(function () {
            expect(pageTitle).toEqual(expectedTitle);
        });
    });
});

Answer №3

As mentioned in your response, the issue stemmed from not allowing enough time for the page to fully load. I find the method name for driver.wait somewhat misleading as it suggests waiting for a specific duration before proceeding, which is not accurate. The wait function serves as a timeout only if the promise does not resolve. For actual waiting, you should utilize driver.sleep(1000) and then set your expectations as illustrated below:

driver.sleep(1000).then(function () {
   return driver.getTitle().then(function (title) {
       expect(title).toBe('webdriver - Google Search');
       done();
   });
});

(Given that you were utilizing done in your query, I assume Jasmine 2.0 and done)

I trust this clarifies things for you.

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

Tips for passing parameters in an AJAX request

I have a single AJAX call that requires passing parameters to my function. Below is the AJAX call implementation: $.ajax({ url: 'lib/function.php', data: { action: 'getStoreSupplyItems', id: store_id, ...

Using Selenium WebDriver to manage dynamic ckEditors

Currently, I am engaged in web scraping using Selenium in Java for a particular website. The pages I am scraping often contain ckeditor elements. So far, I have been using JavaScript and the javascriptexecutor executescript method to extract data from the ...

Obtain the dropdown menu links for every row in a table using Python3 along with Selenium

Seeking assistance as a beginner in Python, I am attempting to automate the downloading process of old newspaper archives from a specific website () using the script provided below. Despite my efforts, I have encountered difficulty in getting the script t ...

Error in React JS: TypeError - Attempting to extend a class with an undefined value, which is not a

I am new to React and experimenting with a code example on https://jscomplete.com/repl. Currently, my code appears as follows: let data = [ { name:"Paul O’Shannessy", avatar_url:"https://avatars1.githubusercontent.com/u/8445?v=4", c ...

Having difficulty retrieving items from an array of objects

After making a call to an API, I stored the response in my state array called mydata by pushing each element of the response (which is an array of objects) onto it. state={ mydata:[] } componentDidMount() { const headers = { "Conte ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Tips on saving extracted information into separate lists

Below is the code snippet I am working with: lokk = [] nums = 7 for _ in range(nums): inner = driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_at ...

Finding the identifier of a dynamically generated text input using PHP

I am looking to create a page similar to this On this page, users can add multiple entries for date, site, start time, end time, and hours amount by clicking the + button, and remove entries using the - button. How can I retrieve the input values in PHP? ...

The CSS animation spills out of the div container

I am encountering an issue with my code where the borders are not displaying as expected. The screen is divided into 8 equal parts, each of which should have a ripple effect. While everything works well in Chrome, Mozilla, Opera, and Safari, the ripple eff ...

Determining if an element is empty in C#

When trying to input data into an input field in a form, it works fine. However, I need to first check if the field is empty before proceeding. My initial attempt was: string Result = Driver.FindElement(By.XPath("//input[@aria-labelledby='i1']")) ...

What could be causing the AngularUI bootstrap datepicker to not appear?

Exploring the popup datepicker demo from angularUI bootstrap, which is embedded in their page and works perfectly. However, when I tried to create a minimal plunker here, the button click does not open the calendar. Any thoughts on what might be causing th ...

step-by-step guide on implementing autocomplete using google.maps.places.autocomplete in ExtJS

Just to clarify... I initially wrote a code that was error-free before editing this post. However, after reading a comment on creating a Minimal, Complete, and Verifiable example, I became confused. My minimal script did not work properly, I couldn't ...

Upon initiating a second user session, NodeJS yields contrasting MySQL outcomes

As a novice in NodeJS and Express, I find myself stuck on what seems to be a trivial issue. Despite my best efforts, I have been unable to resolve the problem on my own. My aim is to create a basic web application that allows user authentication and displ ...

Certain images are not being retrieved by Express on Linux, although they are functioning properly on Windows

When using a template to display HTML code, everything works smoothly on Windows. However, when transferring the code to a Linux machine, an issue arises - "Cannot GET /SmallVacImages/1.jpg". It seems that the index.html file can load images from the publi ...

Tips for concealing a div when the mouse is moved off it?

My goal is to create a simple hover effect where hovering over an image within a view filled with images displays an additional div. This part works as expected. However, I'm facing issues when trying to hide the same div when the user moves out of t ...

retrieve the item that contains a vacant array within a specific record

I have a set of nested object documents that I need to retrieve and group based on the nested objects with empty arrays using aggregation. Let me provide a more detailed explanation-- suppose my collection consists of the following documents -- Document ...

Retrieve the values from input elements that have been created dynamically

I wrote some JavaScript code to generate dynamic input elements. Here's an example: while(count<n-2){ if(dataArray[count+1]=='String') var txt = "Argument:"+(count+1)+", Prefix: <input type=\"text\" name=\"prefix[ ...

Is there a jQuery/JavaScript alternative to each() specifically designed for handling a single element?

I'm looking to streamline this code snippet so that I can retrieve only the first item from an object (data). Any suggestions on how I can achieve this more efficiently than using each() method for just one item? $(data).each(function(num, entry){ ...

What is the process to transfer data from JavaScript to HTML within a Laravel environment?

I am attempting to transfer a value from JavaScript to HTML as a variable. In order to do this, I am retrieving the value from a Laravel PHP controller. JavaScript $("ul.nav-tabs > li > a").click(function() { var id = $(this).attr("href").repla ...

Having trouble with Silverlight running JavaScript?

When I try to call a JavaScript function from a SL component using the HtmlPage.Window.Invoke api, it works fine if the function is defined in the page (html). For example: HtmlPage.Window.Invoke("publishValue", topic, jsonObject); However, if I place th ...