# `@shopify/loom-plugin-jest`

This package provides a `loom` plugin that runs the [Jest](https://jestjs.io) test runner as part of the `loom test` command.

## Installation

```sh
yarn add @shopify/loom-plugin-jest --dev
```

## Usage

Add `jest` to your loom workspace plugins. Jest is a workspace plugin, however most of its configuration through hooks occurs on the per-project level.

```js
import {createWorkspace} from '@shopify/loom';
import {jest} from '@shopify/loom-plugin-jest';

// `createWorkspace` may be `createPackage`, or `createWebApp` if your workspace
// consists of a single project
export default createWorkspace((workspace) => {
  workspace.use(jest());
});
```

### Jest Test Setup Files

By default this plugin sets Jest's [`setupFiles`](https://jestjs.io/docs/configuration#setupfiles-array) to look for setup files in `tests/setup/environment.*` and [`setupFilesAfterEnv`](https://jestjs.io/docs/configuration#setupfilesafterenv-array) to look for setup files in `tests/setup/tests.*` at the root of your workspace, and at the root of each project you have configured (if you have only one loom config then this is the same directory). You can modify this list of files by adjusting the `jestSetupFiles`, `jestSetupFilesAfterEnv` project hooks (for per-project files) and the `jestSetupFiles`, `jestSetupFilesAfterEnv` workspace hooks (for all projects in the workspace).

### Jest Environment

The default environment is [`node`](https://jestjs.io/docs/configuration#testenvironment-string). If you need access to a browser-like environment (such as having access to `window`) then you will need to use the `jsdom` environment. You can set this on a per-project basis with the `jestTestEnvironment` hook, which sets Jest's [`testEnvironment`](https://jestjs.io/docs/configuration#testenvironment-string) option:

```js
import {createPackage, createProjectPlugin} from '@shopify/loom';

export default createPackage((pkg) => {
  pkg.use(jestAdjustments());
});

function jestAdjustments() {
  return createProjectPlugin('JestAdjustments', ({tasks: {test}}) => {
    test.hook(({hooks}) => {
      hooks.configure.hook((configuration) => {
        configuration.jestTestEnvironment?.hook(() => 'jsdom');
      });
    });
  });
}
```

### Jest Test Runner

The default test runner is [`jest-circus/runner`](https://jestjs.io/docs/configuration#testrunner-string). If need to use a different test runner - such as the legacy test runner from before Jest 27 `jest-jasmine2` - you can set this on a per-project basis with the `jestTestRunner` hook, which sets Jest's [`testRunner`](https://jestjs.io/docs/configuration#testrunner-string) option:

```js
import {createPackage, createProjectPlugin} from '@shopify/loom';

export default createPackage((pkg) => {
  pkg.use(jestAdjustments());
});

function jestAdjustments() {
  return createProjectPlugin('JestAdjustments', ({tasks: {test}}) => {
    test.hook(({hooks}) => {
      hooks.configure.hook((configuration) => {
        configuration.jestTestRunner?.hook(() => 'jest-jasmine2');
      });
    });
  });
}
```

### Custom Transforms

By default JavaScript and TypeScript is supported. If you need to support additional file types you can use custom transforms - you can set these on a per-project basis with the `jestTransform` hook, which sets Jest's [`transform`](https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object) option:

```js
import {createPackage, createProjectPlugin} from '@shopify/loom';

export default createPackage((pkg) => {
  pkg.use(jestAdjustments());
});

function jestAdjustments() {
  return createProjectPlugin('JestAdjustments', ({tasks: {test}}) => {
    test.hook(({hooks}) => {
      hooks.configure.hook((configuration) => {
        configuration.jestTransform?.hook((transforms) => ({
          ...transforms,
          '\\.txt$': 'path-to-custom-transformer',
        }));
      });
    });
  });
}
```

### Hooks

This plugin adds the following hooks to `JestProjectHooks`:

- `jestModuleFileExtensions`, `jestModuleNameMapper`, `jestSetupFiles`, `jestSetupFilesAfterEnv`, `jestTestEnvironment`, `jestTestRunner`, `jestTransform`, `jestWatchPathIgnorePatterns`: Convineince hooks that map to the Jest config options with the same name without the "jest" prefix (e.g. the `jestTestEnvironment` hook maps to the [`testEnvironment`](https://jestjs.io/docs/configuration#testenvironment-string) Jest option).

  Modifying one of these hooks is functionally identical to modifying the corresponding key in the object that is returned by the `jestConfig` project hook.

  ```js
  import {createProjectPlugin} from '@shopify/loom';

  function demoPlugin() {
    return createProjectPlugin('Demo', ({tasks: {test}}) => {
      test.hook(({hooks}) => {
        hooks.configure.hook((configure) => {
          // Configure the test environment
          configuration.jestTestEnvironment?.hook(() => 'jsdom');
        });
      });
    });
  }
  ```

- `jestConfig`: The [Jest per-project configuration](https://jestjs.io/docs/configuration#projects-arraystring--projectconfig) for single project. Use this to manipulate the Jest config for options that are not exposed as convinience hooks.

  ```js
  import {createProjectPlugin} from '@shopify/loom';

  function demoPlugin() {
    return createProjectPlugin('Demo', ({tasks: {test}}) => {
      test.hook(({hooks}) => {
        hooks.configure.hook((configure) => {
          // Increase the test timeout to 10 seconds
          configure.jestConfig?.hook((config) => ({
            ...config,
            testTimeout: 10000,
          }));
        });
      });
    });
  }
  ```

This plugin adds the following hooks to `JestWorkspaceHooks`:

- `jestSetupFiles` and `jestSetupFilesAfterEnv`: Arrays of files that shall be added to every project's [`setupFiles`](https://jestjs.io/docs/configuration#setupfiles-array) and [`setupFilesAfterEnv`](https://jestjs.io/docs/configuration#setupfilesafterenv-array) respectively. `jestSetupFiles` defaults to `tests/setup/environment.*` and `jestSetupFilesAfterEnv` defaults to `tests/setup/tests.*`. These paths are relative to the workspace root.

  ```js
  import {createWorkspacePlugin} from '@shopify/loom';

  function demoPlugin() {
    return createWorkspacePlugin('Demo', ({tasks: {test}}) => {
      test.hook(({hooks}) => {
        hooks.configure.hook((configure) => {
          // Add ./path/to/my-custom-setup.ts to setupFiles
          configure.jestSetupFiles?.hook((files) => [
            ...files,
            './path/to/my-custom-setup.ts',
          ]);
          // Add ./path/to/my-custom-setup-after-env.ts to setupFiles
          configure.jestSetupFilesAfterEnv?.hook((files) => [
            ...files,
            './path/to/my-custom-setup-after-env.ts',
          ]);
        });
      });
    });
  }
  ```

- `jestConfig`: The final [Jest configuration object](https://jestjs.io/docs/configuration) that is executed. This contains all projects.

  ```js
  import {createWorkspacePlugin} from '@shopify/loom';

  function demoPlugin() {
    return createWorkspacePlugin('Demo', ({tasks: {test}}) => {
      test.hook(({hooks}) => {
        hooks.configure.hook((configure) => {
          // Configure the coverage output directory
          configure.jestConfig?.hook((config) => ({
            ...config,
            coverageDirectory: './some-path',
          }));
        });
      });
    });
  }
  ```

- `jestFlags`: An object of options to convert into command line flags for the `jest` command. These options are camelcase versions of their [CLI counterparts](https://jestjs.io/docs/cli).

  ```js
  import {createWorkspacePlugin} from '@shopify/loom';

  function demoPlugin() {
    return createWorkspacePlugin('Demo', ({tasks: {test}}) => {
      test.hook(({hooks}) => {
        hooks.configure.hook((configure) => {
          // Always diable watch mode
          configure.jestFlags?.hook((flags) => ({
            ...flags,
            watch: false,
          }));
        });
      });
    });
  }
  ```
