Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below:

import { suite, test, slow, timeout, skip, only } from 'mocha-typescript';
import chai = require('chai');

var jsdom = require('jsdom');
var Paho: any;
const expect: any = chai.expect;
const host: string = '127.0.0.1';
const port: number = 1384;
const clientId1: string = 'testid1';
const clientId2: string = 'testid2';

let client1;
let client2;

describe('test', function () {
  it('should', function (done) {
    // emulate browser window, which is required by Paho
    jsdom.env("<html><body></body></html>", [],
      function (err: any, window: any) {
        // when window is ready, require Paho and
        // initialize with built window
        Paho = require('ng2-mqtt/mqttws31').jsdom(window);
        // This does not work -> exception in mqttws31.js: window is not defined
        client1 = new Paho.MQTT.Client(host, port, clientId1);
        client1.connect({ onSuccess: () => { expect(true).to.be.true; done(); }, onFailure: () => { expect(false).to.be.true; } })
        done();
      });
  });
});

However, the issue arises when trying to require Paho inside the callback function of jsdom.env(), leading to an exception in mqttws31.js stating "window is not defined". If anyone has a solution to this problem to successfully run the Paho Client in a non-browser environment, please share your insights!

Thank you in advance!

Answer №1

Check out this NPM module called Mochify. It's similar to what you might need. Since Node.js doesn't come with browser globals, using a library that can integrate these globals into your testing environment is essential.

I don't have much experience with Mocha, but I've experimented with Karma and found this library useful as well here.

Another option is to use an external service like BrowserStack which can be helpful for testing across different browsers here

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

How to format decimals in Typescript/Angular with a pipe: comma or dot?

I've recently developed a custom pipe and I'm looking to enhance it by adding commas or periods to thousands values. For instance, 1000 should be displayed as either 1,000 or 1.000. Here is the code snippet for my custom pipe: import { Pipe, Pi ...

Sending a POST request with parameters using HttpClient

My current challenge involves making a POST request to an endpoint that requires query string parameters instead of passing them in the body of the request. const params = new HttpParams() .set('param1', '1') .set('param2' ...

What is the reason that setState functions properly when parsing each key separately, but fails when passed as an object?

Currently, I am delving into the world of React and TypeScript, but I have encountered a problem when trying to pass an object with a specific type in order to update the state. For some reason, the state remains unchanged. My approach involves using the ...

How can I extract only certain keys from a large JavaScript object while keeping the code concise?

Simply put, I aim to streamline objects by discarding unnecessary keys. Imagine a scenario where a third party API sends back JSON data with numerous attributes that hold no importance to you. obj = { name: ..., id: ..., description: ..., blah: .. ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Function for swapping out the alert message

I am searching for a way to create my own custom alert without interfering with the rendering or state of components that are currently using the default window.alert(). Currently working with React 15.x. function injectDialogComponent(message: string){ ...

The Link component in the router dom should only be active when validation passes successfully

I am looking for a way to prevent the Link component in react-router-dom from functioning until all validations are successfully completed. Removing the link allows the validation to work as intended. I have come across something related to ifValidate, bu ...

Populate the AngularJS scope with a dynamically generated array

My Angular Application is functioning properly with <script> var app = angular.module('MyApp', []); app.controller('myCtrl', function ($scope, $sce) { $scope.urls = [ { "url": $sce.t ...

Adjusting MongoDB settings to permit cross-origin requests

I'm still new to using MongoDB, so I'm in the process of familiarizing myself with it. My current goal is to send a JSON object to MongoDB from the client side using the JavaScript code below. var addUserButton = document.getElementById('a ...

How to merge text (string) with date in HTML using JavaScript

I am attempting to blend a day with the phrase "this is the day" in HTML. I gave it a shot, but the concatenation didn't work as expected. ...

What is the best way to access a specific attribute of an HTML element?

Within my ng-repeat loop, I have set a custom attribute like this: <div ng-repeat="item in itemsList" stepType="{{item.stepType}}"> {{item.itemValue}} </div> The possible values for item.stepType are 'task' or 'action ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Enable tabber upon clicking on the navigation bar

Hello there, I am facing an issue with my website's navigation. I have a navigation bar with the unique id #nav and I want to activate a specific tab based on the clicked navigation list item. The HTML structure of the navigation #nav looks like this: ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

Change the source of another element when clicked

Check out the fixed version of previously broken code here I am facing challenges in changing an attribute on another element from a click function sniping $('#black').click(function() { $('#blackbox').slideToggle('slow&apos ...

Link embedded in prism formatting, encased in code snippet

In the HTML template, I have the following code snippet: <pre> <code class="language-markup"> {% filter force_escape %} <Item> <MarkUp><a href="http://google.com">Google</a></MarkUp> <No ...

Using jQuery within an Angular Controller: The specific function $(...).overhang is not recognized in this context

Recently, I decided to integrate overhang.js into my application because of its appealing alert messages. Initially, it seemed like a simple task... All I needed to do (or so I thought) was replace the line in my controller, alert("An HTTP request has be ...

Converting blobs to strings and vice versa in Javascript

After successfully converting a blob to a string using FileReader, the challenge now is to convert it back: var reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { base64data = reader.result; var blobToSend ...