Mocha might be postponing the fulfillment of Chai expectations

As a beginner in test driven development using mocha, selenium, and chai, I am seeking feedback on whether my approach is correct. Below is an excerpt from my functional_tests.js file:

test.it('Hamid visits the first page of tests', function(){
        // Hamid visits the home page of the test platform he heard about
        driver.get('file:///home/marouane/Projects/iframe_test/test_template.html') ;

        // he noticed the title and the header of the page mention Test Template
        driver.getTitle().then(function(title){
            expect(title).to.contain('Test Template');
        });

        driver.findElement(webdriver.By.tagName('h1')).then(function(element){
            expect(element).to.contain('Test Template');
        });
        // he is invited to enter a URL for the page he wants to test
        driver.findElement(webdriver.By.id('input-url'), function(element){
             expect(element).to.equal('Enter a url');
        });
    

Here is the html page I am testing:

<!DOCTYPE html>
    <html>
    <head>
        <title>Test Template</title>
    </head>
    <body>
    <h1></h1>
    </body>
    </html>
    

While expecting an assertion error on the second chai expectation, I encountered this error instead:

NoSuchElementError: Unable to locate element: {"method":"id","selector":"input-url"}.

I suspect I might be making a mistake and that the callback functions are being deferred.

Answer №1

While I am unable to execute your code directly, after reviewing it, I have identified two key issues:

  1. The callback function in your it is asynchronous, but you have not utilized the done callback to signify the completion of the test. Even though WebDriverJS employs a promise style that may appear synchronous and uses "control flow" to make asynchronous code seem synchronous, WebDriverJS inherently operates asynchronously.

  2. You have mixed two different styles of calling WebDriverJS functions - promises and continuations. The calls to driver.get, driver.getTitle, and the first call to driver.findElement use promises. However, the last call to driver.findElement utilizes a continuation instead of a promise. This inconsistency causes your expect calls to execute out of order.

To address these issues, consider implementing the following adjustments:

test.it('Hamid visits the initial test page', function(done){
    driver.get('file:///home/marouane/Projects/iframe_test/test_template.html') ;

    driver.getTitle().then(function(title){
        expect(title).to.contain('Test Template');
    });

    driver.findElement(webdriver.By.tagName('h1')).then(function(element){
        expect(element).to.contain('Test Template');
    });

    driver.findElement(webdriver.By.id('input-url')).then(function(element){
         expect(element).to.equal('Enter a url');
         done();
    });
});

These changes involve adding the done parameter and invoking done() within the appropriate callback function, as well as ensuring consistent usage of promises for all driver.findElement calls.

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

Rendering sibling components on Multiple Select Material UI in React

Here is my current challenge: I am trying to implement a multiple select feature with checkboxes in React using Material UI. The desired outcome should resemble the image linked below: https://i.stack.imgur.com/TJl8L.png I have structured my data in an a ...

My attempt to use the Redux method for displaying data in my testing environment has not yielded

I've been attempting to showcase the data in a Redux-friendly manner. When the advanced sports search button is clicked, a drawer opens up that should display historical data when the search attributes are selected. For this purpose, I implemented the ...

Troubleshooting Python Selenium Code: Identifying and Correcting Errors

Can someone explain why this snippet of code opens Mozilla twice and doesn't close it after finishing? I'm also a bit confused as to why the login function is within a class instead of being a standalone function. > import unittest from selen ...

Display chart labels are constantly visible in Vue Chart JS

In my Vue.js JavaScript application, I am working on setting up a chart where I want the labels and chart information to be visible at all times without requiring mouse hover. Check out this image of the chart. This is the code snippet for my chart: < ...

Regulations for the Web Address of the Interactive Feature in AJAX

Recently, I decided to experiment with AJAX while trying to incorporate form validation from a database before allowing users to submit content. However, I encountered an issue with the URL segment of the Open function. It seems that when I use the full ...

Strategies for removing duplicate items from an array of objects

My array consists of objects with the following structure: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', 'de ...

JavaScript code for when either "a," "b," or "c" is true, but not all of them

Hey there, I'm just getting started with JavaScript! I'm working on creating a syntax to determine if only one of three variables is present. if a and (not b or not c) or b and (not a or not c) or c and (not a or not b) ...

Error: Trying to use 'search' before it has been initialized causes a ReferenceError

Every time I run my code, I encounter this reference error but I can't figure out what's causing it. ReferenceError: Cannot access 'search' before initialization App C:/Users/GS66/Desktop/IN20/IFN666/week4/src/App.js:60 57 | 58 | expor ...

"Running `npm test` always seems to linger forever without completing

My unit tests are run using mocha, and I typically use npm test to execute them. Inside my package.json, I have defined the following scripts: "pretest": "NODE_ENV=test node migrate all", "test": "DEBUG= NODE_ENV=test mocha --recursive", When I directly ...

Yet another interactive JQuery feature found within the JQuery UI Tabs framework, utilizing seamless Ajax page loading

Currently, I am using JQuery U Tabs with Ajax Page Calls. In my Pages, I have a custom scroller that is functioning correctly. Additionally, I have an ajax search table that works when the page is loaded by itself in the browser but not when called within ...

Unable to locate image in React framework

When attempting to display an image, I encountered a 404 error even though the folder containing it is being served properly. Code snippet from JSX file: render: function(){ ... return <button type="button" id="powerButton" onClick={this.someFun}>& ...

Chrome does not allow accessing or setting the `scrollTop()` property for elements with `position: absolute`

When using the JS Fiddle provided, it was discovered that clicking the link in the sidebar scrolls the page to 400px down in Firefox, but this functionality does not work in Chrome. Check out the JS Fiddle here If I am unable to modify the HTML or CSS, i ...

What is the best way to retrieve a list of unchecked checkboxes in a Razor Page model?

Currently, I am working on a razor page using .NET Core 7. I have encountered an issue where I am unable to pass values of 1, 2, and 3 for unchecked checkboxes from the HTML page to the page model in the post method. When the user clicks the submit button ...

Refresh an iframe using Javascript

Hey there, I could really use some assistance with this code. It works perfectly for reloading an iframe using an id, but I'm struggling to figure out how to make it work with a class so that I can reload multiple iframes. Alternatively, I'd like ...

confirm validity prior to executing controller logic

Looking to develop an Express REST API and in need of validating request params and the request body. The router file manages all routes. When accessing localhost:3000/users, the router would redirect to app.use('/users', require(`./routes/user ...

Does using react useMemo offer better performance compared to using a module-level variable?

I'm in need of hard-coding some data for a react component without any changes, and I want to do it in the most efficient way possible. When I say efficient, I mean fast execution with minimal system resource usage. I have two methods in mind: // Meth ...

having trouble retrieving information from the input field

I'm having trouble retrieving the user's input from the input field, can someone assist me with this issue? I can't seem to identify what the problem is here. var ftemp = document.getElementById("Farenheit").value; <td> <i ...

Expand the accordion to reveal all the content

I'm facing an issue with my accordion where a scrollbar appears in every content section. To fix this, I tried setting overflow: hidden in the CSS: .ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: hidd ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...

What is the best way to adjust the width of these elements for a perfect fit?

I'm currently working on a website where I have arranged squares in a grid layout. My goal is to make these squares perfect, with equal width and height. The only issue I'm encountering is that they tend to change between fitting two and three sq ...