Search code examples
javascriptselenium-webdrivercucumber

How can I stop my Cucumber.js steps running all at once?


I want to write a Cucumber.js test that tests a search form on my site. Using Selenium Webdriver I can enter a term into the search field and hit return, no issue. However, after this step the following steps run before the the results page loads.

How can I get the next steps to run after the results page is loaded?

My code is:

const { When, Then, AfterAll, Given } = require('@cucumber/cucumber');
const assert = require('assert');
const { Builder, By, until, Key } = require('selenium-webdriver');

const driver = new Builder()
    .forBrowser('firefox')
    .build();

Given('I am on the search page',  async function () {
    driver.wait(until.elementLocated(By.tagName('h1')));
    await driver.get('https://www.awebsite.com/search');
});

When('I enter the term Honda', async function() {
    await driver.findElement(By.className('search-input')).sendKeys('Honda', Key.RETURN);
});


Then('the search should return results', async function() {
    let results = await driver.findElement(By.className("search-container_results"));
    let count = await driver.findElement(By.className("search-results_count")).getText();
    assert.equal(count, "5 results");
});

AfterAll(async function(){
    await driver.quit();
});

Solution

  • I eventually found I could only achieve this using Explicit Waits with elements.

    With the case above I used until.elementTextContains() to ascertain if the text in an element had changed, before continuing with the test.

    Since the element its self is always present, I also used unit.stalenessOf().

    So, I altered the Then() step to be:

    Then('the search should return results', async function() {
        await driver.wait(until.stalenessOf(driver.findElement(By.className("search-container_results"))));
        await driver.wait(until.elementTextContains(driver.findElement(By.className("search-container_results")), 'Honda'));
        let count = await driver.findElement(By.className("search-results_count")).getText();
        assert.equal(count, "5 results");
    });