Search code examples
intern

How can I run some code in Node prior to running a browser test with Intern?


With Intern, how can I run some setup code in Node prior to running browser tests, but not when running Node tests? I know that I could do that outside of Intern completely, but is there anything that's a part of Intern that could handle that?

For a more concrete example: I'm running tests for an HTTP library that communicates with a Python server. When running in Node, I can run spawn("python", ["app.py"]) to start the server. However, in the browser, I would need to run that command before the browser begins running the tests.

Phrased another way: is there a built-in way with Intern to run some code in the Node process prior to launching the browser tests?


Solution

  • By default, Intern will run the plugins configured for node regardless of which environment you're running in.

    So, you could create a plugin that hooks into the runStart and runEnd events like this:

    intern.on("runStart", () => {
      console.log("Starting...");
      // Setup code here
    });
    
    intern.on("runEnd", () => {
      console.log("Ending...");
      // Teardown code here
    });
    

    These handlers will run inside the Node process, and thus have access to all the available Node APIs.

    Additionally, you can detect which environments are being tested by looking at intern.config.environments:

    {
      environments: [
        {
          browserName: 'chrome',
          browserVersion: undefined,
          version: undefined
        }
      ]
    }
    

    By looking at the environments, you can determine whether or not you need to run your setup code.