let { COPY_KARMA } = process.env;

let { tmpdir } = require("os");

let { writeFile } = require("./fs");

let { join } = require("path");

let { randomBytes } = require("crypto");

let { exec, spawn } = require("./child_process");

let { interceptStdout } = require("./intercept_stdout");

let { Server } = require("karma");

function generateRandomFilePath () {
  return join(
    tmpdir(),
    randomBytes(20).toString("hex") + ".js");
}

async function createKarmaTest (launcherOptions, testFunction) {
  let tmpTestFile = generateRandomFilePath();

  let config = {
    files:         [tmpTestFile],
    frameworks:    ["mocha"],
    browsers:      ["jsdom"],
    singleRun:     true,
    jsdomLauncher: launcherOptions
  };

  await writeFile(tmpTestFile, `
    it("dummy description", ${testFunction.toString()});
  `);

  await interceptStdout({ passthrough: COPY_KARMA === '1' }, function () {
    return new Promise((resolve, reject) => {
      new Server(config, function(exitCode) {
        if (exitCode === 0) {
          resolve();
        } else {
          reject(new Error("The Karma test errored. Run with COPY_KARMA=1 to see Karma's output."));
        }
      }).start();
    });
  });
}

module.exports = {
  createKarmaTest
};

@@ -319,16 +319,445 @@
 rma%22);%0A%0A
+// As per 3.0.0 %5B1%5D, Karma will attempt to clear the console of any content.%0A// With jsdom and node, this translates into %5E%5B1%5D;1H%5E%5B0J and your terminal is%0A// cleared. This isn't desirable and thus we remove the method.%0A//%0A// %5B1%5D https://github.com/karma-runner/karma/blob/v3.0.0/client/karma.js#L223%0Aconsole.clear = null;%0A%0Aif (console.clear) %7B%0A  console.error(%22Unable to remove console.clear(), exiting%E2%80%A6%22);%0A  process.exit(1);%0A%7D%0A%0A
 function

Remove console.clear during test execution