Mark's notes on software development

ESM + TypeScript + Serverless. Part 2: Configuring Jest

Welcome back! Following our initial journey detailed in "Building a Serverless Node.js Application with ESM and TypeScript in 2024," this article is the second installment in our series. Today, we're focusing on elevating your TypeScript serverless application by integrating Jest for testing. I'll guide you through the process of incorporating Jest, making it straightforward and impactful for your project's quality. Let's delve into the seamless integration of Jest into your development workflow.

Step-by-Step Tutorial: Integrating Jest with ESM Support in a TypeScript Project

Installing Dependencies

First, let's install Jest along with its TypeScript support and utilities. Run this command:

yarn add --dev jest @types/jest ts-jest cross-env

This command installs Jest for testing, @types/jest for TypeScript support, ts-jest for transpiling TypeScript tests, and cross-env for setting environment variables across platforms.

Creating the Jest Configuration

Next, create the Jest configuration file. This file specifies settings like the testing environment, timeouts, coverage options, and most importantly, ESM module support.

/** @type {import('jest').Config} */
const config = {
  testEnvironment: 'node',
  testTimeout: 30_000,
  collectCoverage: true,
  clearMocks: true,
  coverageDirectory: 'coverage',
  coverageProvider: 'v8',
  
  // ESM support:
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '^.+\\.m?[tj]sx?$': [
      'ts-jest',
      {
        useESM: true,
      },
    ],
  },
};
export default config;

This configuration ensures Jest can handle ESM modules.

Setting Up the Test Script in package.json

Add a script to run the tests, considering environmental variables on different platforms.

"scripts": {
  "test": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest"
}

This allows running Jest tests with ESM support enabled.

Writing the Test

Now, write a test to verify the functionality of your code.

// handler.test.js
import { handler } from './handler.js';

describe('Handler', () => {
  it('should return 200', async () => {
    const rawResponse = await handler({});
    expect(rawResponse.statusCode).toBe(200);

    const response = JSON.parse(rawResponse.body) as { message: string; };
    expect(response.message).toBe('Hello, World!');
  });
});

Running the Tests

Finally, execute the tests using the command yarn test.

Each of these steps is tailored to address the challenge of ESM support in Jest, which is crucial for modern TypeScript web development.

#esm #jest #tutorial #typescript