Skip to content

Instantly share code, notes, and snippets.

@designervoid
Forked from solkaz/detox-ts.md
Last active May 6, 2021 11:38
Show Gist options
  • Save designervoid/0e3253663f2e78deca8db0a9d0f57370 to your computer and use it in GitHub Desktop.
Save designervoid/0e3253663f2e78deca8db0a9d0f57370 to your computer and use it in GitHub Desktop.
Writing Detox Tests with TypeScript

Usage

This guide assumes you've got a project using Detox with Jest, and you want to write your Detox tests in TypeScript.

  • Refer to this guide if you need to set up such a project.

1. Add TypeScript + ts-jest to package.json

We'll be using ts-jest to run Jest tests with TypeScript.

npm install --save-dev typescript ts-jest

2. Configure Jest to use ts-jest

Modify your Jest configuration (e2e/config.json by default) to include the following properties

{
  "preset": "ts-jest",
  "testEnvironment": "node",
  "setupFilesAfterEnv": ["./init.ts"],
  "testRegex": "\\.e2e\\.ts$"
}

NB: this is mostly the same output of running ts-jest config:init, with setupTestFrameworkScriptFile being the only added property.

3. .js -> .ts

Convert all files in the e2e directory ending in .js to .ts

4. Add typings for Detox, Jest, and Jasmine

Add typings for Detox, Jest, and Jasmine (the latter two are used in init.ts), as well as for other modules that you use in your Detox tests.

npm install --save-dev @types/detox @types/jest @types/jasmine

5. Writing tests

It's recommended that you import the Detox methods instead of their globally defined counterparts, to avoid a typing issue between Detox and Jest. This can be enforced by calling detox.init with { initGlobals: false }

Your init.ts would look simliar to this:

import {cleanup, init} from 'detox';
const adapter = require('detox/runners/jest/adapter');

const config = require('../package.json').detox;

// tslint:disable-next-line:no-import-side-effect
import "jasmine";

jasmine.getEnv().addReporter(adapter);

jest.setTimeout(120000);
 
beforeAll(async () => {
  console.log(config);
  await init(config);
});

beforeEach(async () => {
  await adapter.beforeEach();
});

afterAll(async () => {
  await adapter.afterAll();
  await cleanup();
});

Note: the global constants are still defined in the typings, so using the globals will not result in a tsc error.

Your tests would then import the Detox methods from the detox module like so:

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

describe('Example', () => {
  beforeAll(async () => {
    await device.launchApp({permissions: {camera: 'YES'}, newInstance: true});
  });
  
  it('Something Test', async () => {
    // ...
  });
});

Note: @types/detox is maintained by the community and not by Wix.

You should now be able to run your Detox tests, written in TypeScript!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment