<!DOCTYPE HTML>
<html>
<!--
  -->
<head>
  <title>Test for Bug 1317266</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script src="error_reporting_helpers.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1317266">Mozilla Bug 1317266</a>
<p id="display"></p>
<div id="content" style="display: none">

</div>
<pre id="test">
</pre>

<script class="testbody" type="text/javascript">
SimpleTest.requestFlakyTimeout("Forcing a race with the cycle collector.");

add_task(function setupPrefs() {
  return SpecialPowers.pushPrefEnv({"set": [
    ["dom.serviceWorkers.enabled", true],
    ["dom.serviceWorkers.testing.enabled", true],
  ]});
});

add_task(async function test_worker_ref_gc() {
  let registration = await navigator.serviceWorker.register(
    "lazy_worker.js", { scope: "./lazy_worker_scope_timeout"} )
    .then(function(reg) {
      SpecialPowers.exactGC();
      var worker = reg.installing;
      return new Promise(function(resolve) {
        worker.addEventListener('statechange', function() {
          info("state is " + worker.state + "\n");
          SpecialPowers.exactGC();
          if (worker.state === 'activated') {
            resolve(reg);
          }
        });
      });
    });
  ok(true, "Got activated event!");

  await registration.unregister();
});

add_task(async function test_worker_ref_gc_ready_promise() {
  let wait_active = navigator.serviceWorker.ready.then(function(reg) {
    SpecialPowers.exactGC();
    ok(reg.active, "Got active worker.");
    ok(reg.active.state === "activating", "Worker is in activating state");
    return new Promise(function(res) {
      reg.active.onstatechange = function(e) {
        reg.active.onstatechange = null;
        ok(reg.active.state === "activated", "Worker was activated");
        res();
      }
    });
  });

  let registration = await navigator.serviceWorker.register(
    "lazy_worker.js", { scope: "."} );
  await wait_active;
  await registration.unregister();
});

add_task(async function cleanup() {
  await SpecialPowers.popPrefEnv();
});
</script>
</body>
</html>
