Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 切换navigator.online_Javascript_Phantomjs_Karma Runner - Fatal编程技术网

Javascript 切换navigator.online

Javascript 切换navigator.online,javascript,phantomjs,karma-runner,Javascript,Phantomjs,Karma Runner,我正在使用phantomjs运行与karma的集成测试。如何模拟脱机模式 似乎我无法更改“navigator.online”,并且在phantomjs的脱机模式下找不到任何内容 编辑: 应用程序正在向外部位置发送消息。当浏览器脱机时,它应该停止发送消息并将其存储在队列中。一旦连接恢复,它应该从队列发送所有消息 我只是检查“navigator.online”是否返回true或false 也许有更好的方法来实现和测试这一点 如果您有任何建议,我们将不胜感激。navigator.online为只读属性

我正在使用phantomjs运行与karma的集成测试。如何模拟脱机模式

似乎我无法更改“navigator.online”,并且在phantomjs的脱机模式下找不到任何内容

编辑:

应用程序正在向外部位置发送消息。当浏览器脱机时,它应该停止发送消息并将其存储在队列中。一旦连接恢复,它应该从队列发送所有消息

我只是检查“navigator.online”是否返回true或false

也许有更好的方法来实现和测试这一点


如果您有任何建议,我们将不胜感激。

navigator.online
为只读属性。您的组件应该有一个单独的属性,以便您可以在测试中将其设置为false或true(而不是总是直接检查
navigator.online


课程:如果可以的话,不要在代码中使用全局对象,这会使模拟变得更加困难。相反,允许调用方模拟/存根全局对象。

这是我用来控制测试中的
navigator.onLine
方法的代码。我在使用Karma运行的测试中使用它来启动浏览器并启动测试。摩卡是真正的试跑者。以下内容在
before
(aka
beforeAll
)钩子中运行。整个事情(包括
让在线
)的范围是需要它的
描述

我使用两种方法,因为不幸的是,没有办法修改
navigator
,使其在任何地方都能工作。第一种方法适用于Chrome、Firefox、IE、Edge和Opera。第二种方法适用于Safari。相反,第二种方法不适用于铬。因此,我们不能只使用一种或另一种方法

let onLine = true;

function mockNavigatorOnline() {
  const descriptor = {
    get: function getOnline() {
      return onLine;
    },
  };

  // 1st method.
  Object.defineProperty(navigator.constructor.prototype, "onLine",
                        descriptor);

  // Check whether the code above "took". We check both for `true` 
  // and `false`.
  onLine = false;
  let passes = navigator.onLine === onLine;
  onLine = true;
  passes = passes && (navigator.onLine === onLine);

  // 2nd method.
  if (!passes) {
    navigator = Object.create(navigator, { onLine: descriptor });
  }
}
let onLine = true;

function mockNavigatorOnline() {
  const descriptor = {
    get: function getOnline() {
      return onLine;
    },
  };

  // 1st method.
  Object.defineProperty(navigator.constructor.prototype, "onLine",
                        descriptor);

  // Check whether the code above "took". We check both for `true` 
  // and `false`.
  onLine = false;
  let passes = navigator.onLine === onLine;
  onLine = true;
  passes = passes && (navigator.onLine === onLine);

  // 2nd method.
  if (!passes) {
    navigator = Object.create(navigator, { onLine: descriptor });
  }
}