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

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

Sharing environment variables between a React app and an Express.js server that hosts it as a static site can be achieved by setting

My static site react app is hosted under an express server project in a folder called client/build. The oauth redirect uris point to the express server for token retrieval. The react app redirects users to the oauth endpoint, which is also referenced by th ...

Looping through values in VueJS from 100 to 0

I am currently working on creating a power meter that will smoothly transition from 100 to 0 and back again to 100. The idea is for the user to press a button, causing the meter to stop at a random value. I just need some assistance in getting the loop fu ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

Using j Query to create custom masks for various formats with the option to include optional digits

Looking for a way to mask the CVV card number..! The masking should allow for either 3 numbers like xxx 123 or 4 numbers like xxxx 4567 I have attempted to implement this with jQuery mask plugin, but it only allows for 4 characters. How can I enable both ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

The SyntaxError is triggered by the React-Native FlatList component

As a newcomer to React Native, I am facing an issue with refreshing the component to load city names stored in async storage. The error occurs when I utilize the FlatList component for the first time. The specific error message I encountered is: SyntaxE ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

Vue.js is not incrementing the counter as expected

I've encountered an issue with a button that has a click event to increment data value by 5, but instead of adding 5 it is appended by 5. Click here for the code example <div id="react"> <button @click='counter += 5'>Increment& ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

Using AngularJS to encapsulate an externally loaded asynchronous library as a service

Is there a way to wrap a 3rd party library that loads asynchronously into an Angular service? What is the best practice for incorporating such libraries as services in Angular? Currently, I am approaching it like this: angular.module('myAPIServices ...

Using maxCDN to deliver static files within a Node application

Our current project is built using keystone and nunjucks, with all paths to static files following the format /stc/img/someimage.jpg. I am looking for a way to serve these files through middleware in our node server from maxCDN. Is there a solution that ...

Certain rows in the table should maintain a consistent width, while others are allowed to vary

I am dealing with a table containing certain rows Some of these rows are visible, while others are hidden. The visible rows at the start are referred to as: mainTrs. Clicking on a visible row will make all rows with a class matching its id visible. Cli ...

jQuery.get() function is limited to specific types of webpages

I have successfully combined multiple weather APIs on my website, which can be found here. Recently, I started using the weather.gov API and it has been quite effective. However, there are certain data points that I need to extract which the weather.gov A ...