【问题标题】:'window is not defined' when testing Paho MQTT Client with mocha and typescript使用 mocha 和 typescript 测试 Paho MQTT 客户端时出现“未定义窗口”
【发布时间】:2016-12-20 13:58:53
【问题描述】:

我在 Google 上搜索了几天,但找不到任何关于如何测试 Paho MQTT Client 的信息。我以一种天真的方式尝试过,就像这样:

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();
      });
  });
});

但是Paho = require(...)-jsdom.env(...) 的回调函数中的部分会在 mqttws31.js 中抛出异常:“未定义窗口”。有谁知道如何解决这个问题,以便让 Paho 客户端在非浏览器环境中运行?

提前致谢!

【问题讨论】:

    标签: javascript testing typescript mqtt paho


    【解决方案1】:

    https://www.npmjs.com/package/mochify 你可以像这样使用类似的 NPM 模块。就像您可能期望的那样,Node.js 环境本身没有浏览器全局变量,因此请使用一些可以将这些全局变量集成到您的测试环境的库。

    我对 mocha 不是很熟悉,但这里有一个我在 Karma 玩过的库作为参考 https://www.npmjs.com/package/karma-browserify

    或者简单地使用一些外部服务,比如 BrowserStack https://www.npmjs.com/package/browserstack

    【讨论】:

    • 我以为这就是jsdom 的全部意义所在?您知道为什么这在我的示例中不起作用吗?
    猜你喜欢
    • 1970-01-01
    • 2014-11-12
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2016-10-27
    • 2018-10-18
    相关资源
    最近更新 更多