Search code examples
shelljestjsyarnpkgend-to-end

How can I run a shell script as a setup file in Jest?


Something like this. The goal is to start and stop my test server as part of the jest setup so I can do end to end testing with a single command.

"jest": {
  "setupFiles": ["<rootDir>/TestScript.sh"]
} 

Solution

  • I will answer this myself for anyone in the future who is trying to solve the same problem as me.

    Jest config has globalSetup and globalTeardown options. This script will be run once at the beginning of all tests.

    "jest": {
      "globalSetup": "<rootDir>/jestGlobalSetup.js"
    }
    

    In node, you can use the child_process API to run shell scripts from a js file. I ran mine like this in my setup file.

    import { spawn } from 'child_process';
    import cwd from 'cwd';
    
    export default async function setup() {
      process.stdout.write('Starting Server');
    
      // Run this command in shell.
      // Every argument needs to be a separate string in an an array.
      const command = 'foreman';
      const arguments = [
        'start', 
        '-p', 
        '3000', 
        '-f', 
        'Procfile.test',
      ];
      const options = { 
        shell: true, 
        cwd: cwd() 
      };
    
      const server = spawn(
        command, 
        arguments,
        options,
      );
    
      // Then I run a custom script that pings the server until it returns a 200.
      await serverReady();
    }