Experimenting with mocha and Nightmare.js, utilizing traditional syntax and without the use of ES6 features

Here is a real-world example that I am using:

How to Use Nightmare.js without ES6 Syntax and Yield

However, when I include it in a Mocha test, it times out. Here's the code snippet:

describe('Google', function() {
it('should perform tasks', function(done) {
    var startTime = Date.now();
    var nightmareInstance = Nightmare();
    Promise.resolve(nightmareInstance
        .goto('http://google.com')
        .evaluate(function() {
            return document.getElementsByTagName('html')[0].innerHTML;
        }))
    .then(function(htmlContent) {
        console.log("Execution time: " + (Date.now()-startTime) + "ms");
        console.log("Result:", htmlContent);
        expect(htmlContent).to.equal('abc');
        done();
        return nightmareInstance.end();
    }).then(function(result) {

    }, function(error) {
        console.error(error); // throwing an error here won't work
    });
});
});

The issue lies in the fact that done() is never invoked.

Answer №1

To implement the yield function, I rely on the mocha-generators plugin. Below is a suggested code structure for you:

require('mocha-generators').install();

var Nightmare = require('nightmare');
var expect = require('chai').expect;

describe('login test', function() { 

  var nightmare;

  beforeEach(function *() {
    nightmare = Nightmare({
      show: true,
    });

  afterEach(function*() {
    yield nightmare.end();
  });

  it('should navigate to google', function*() {
    this.timeout(5000);

    var result = yield nightmare
      .goto('http://google.com')
      .dosomeotherstuff

    expect(result).to.be('something')
  });

});

If you are using generators, there is no need for 'done' as it is a callback designed for handling asynchronous operations.

Answer №2

To prevent errors and timeouts in your code when using Electron, ensure that the .end() function is placed after the .evaluate() function within the Nightmare promise chain.

describe('Google', function() {
   it('should do things', function(done) {
    var x = Date.now();
    var nightmare = Nightmare();
    nightmare
        .goto('http://google.com')
        .evaluate(() => {
            return document.getElementsByTagName('html')[0].innerHTML;
        })
        .end()
        .then( (html) => {
            console.log("done in " + (Date.now()-x) + "ms");
            console.log("result", html);
            expect(html).to.equal('abc');
            done();
        })
        .catch(done);
    });
});

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

Non-functioning Tooltips on Google Charts

Currently, I am working on integrating Google Chart with ASP.NET and linking it to a SQL Server database. I have encountered an issue while attempting to customize the tool tip. Below is the Header Code: <script src="js/jquery/jquery-1.10.2.js" type=" ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

How can I stop Jquery Mobile from processing the URL hash?

Currently implementing Jquery Mobile in a preexisting web application is posing a challenge. The issue arises as Jquery Mobile is interpreting all URL hashes by default. For example: mysite.com/#foo In this case, the hash 'foo' is being directe ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Looking to alter the CSS of an ID element when hovering over a link on your website?

Irrespective of the positioning of the links in the html, a simple hover effect can trigger changes like switching images or altering backgrounds anywhere on the website. The ideal solution would involve a straightforward method without the need for Javas ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

Utilizing Ajax to dynamically generate unique ID's for multiple checkboxes

I have been working on a website that is almost completed, however, I have come across a new task where I need to select check-boxes in order to archive news items or "blog posts". The concept is to have a check-box next to each blog post and by checking ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Is there a way to ensure that clicking a link_to only opens a partial once?

These are the files I am working with: _comment.haml %div.comment{ :id => "comment-#{comment.id}" } %hr - if current_user && current_user.id == comment.user_id || current_user && current_user.id == reel_user = link_to " ...

Automatically adjusting the top margin of the main content section depending on the variable height of a fixed header

Visit our mobile site here (mobile view) Currently, I have set the margin-top of .main-content based on sticky-animation, which keeps the header fixed at the top on mobile. However, there is a div with a close button (X) that alters its height dynamically ...

Whenever I find myself being redirected to the login page, my goal is to eliminate the bottomTab from view

I'm looking to eliminate the bottom tab when I land on the login page, even though I've set it up for all pages. However, whenever I click on the login button, the tab remains visible. Here is my current code: import React, { useContext } from & ...

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

Managing Emitted Events in Vue.js Components within Components: A Guide

I have created a Toolbar Item component as follows: <template> <div class="flex cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 p-1 shadow-sm transition-all duration-300 hover:scale-110 hover:bg-black ho ...

Refreshing an HTML table using instance variables from a C# class (utilizing jQuery and AJAX)

Explore <script type="text/javascript"> $(document).ready(function () { $("#viewDetails").click(function () { $.ajax( { type: "POST", url: '@Url.Action("GetDetail", "ControllerName")' ...

Is it possible for Jaydata relationships to function seamlessly without the need to be

I am attempting to set up a basic model with Parent -> Child relationships (correctly declared and functioning, I believe). This is my approach: var parent = new $data.Types.Parent(); $data.context.Parents.add(parent); parent.Code = 123; var child = new ...