Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'window is not defined' when testing Paho MQTT Client with mocha and typescript

I googled for days but can't find anything about how to test the Paho MQTT Client. I tried it in a sort of naive way, like that:

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 Paho = require(...)-Part inside the callback function of jsdom.env(...) throws the exception in mqttws31.js: "window is not defined". Has anyone an idea how to solve that, in order to get the Paho Client running in a non-browser environment?

Thanks in advance!

like image 870
jlang Avatar asked Nov 08 '22 04:11

jlang


1 Answers

https://www.npmjs.com/package/mochify You could be using similiar NPM module like this. Like you might expect Node.js environment dosen't have browser globals itself so use some library which can integrate these globals to your testing environment.

I am not very familiar with mocha but here's one more library I have played around in Karma as reference https://www.npmjs.com/package/karma-browserify

Or simply using some external service like BrowserStack https://www.npmjs.com/package/browserstack

like image 67
Jimi Pajala Avatar answered Nov 14 '22 21:11

Jimi Pajala