Write Detox tests in TypeScript


This post goes over how to write Detox tests in TypeScript.

Prerequisites

You have a React Native project with Detox set up.

Setup

Install the typings for detox and jest:

yarn add --dev @types/detox @types/jest

In Detox version 18.1.0 and higher, you don’t need to install @types/detox since Detox provides its own type definitions.

Update e2e/jest.config.js:

 /** @type {import('@jest/types').Config.InitialOptions} */
 module.exports = {
+  preset: 'react-native',
   rootDir: '..',
-  testMatch: ['<rootDir>/e2e/**/*.test.js'],
+  testMatch: ['<rootDir>/e2e/**/*.test.ts'],
   testTimeout: 120000,
   maxWorkers: 1,
   globalSetup: 'detox/runners/jest/globalSetup',
   globalTeardown: 'detox/runners/jest/globalTeardown',
   reporters: ['detox/runners/jest/reporter'],
   testEnvironment: 'detox/runners/jest/testEnvironment',
   verbose: true,
 };

The Jest react-native preset transforms TypeScript with babel-jest.

Rename e2e/starter.test.js to e2e/starter.test.ts:

mv e2e/starter.test.js e2e/starter.test.ts

Update e2e/starter.test.ts and import the detox functions instead of using the globals:

import { by, device, expect, element, waitFor } from 'detox';

Run your E2E tests (assuming you already ran build):

yarn detox test --configuration ios.sim.debug

Voilà! You’re Detox tests should run with TypeScript.

Demo

See example repository.



Please support this site and join our Discord!