ยท testing

Setup electron-mocha with @babel/register and TypeScript

This tutorial teaches you how to write tests for Electron using TypeScript and mocha. You'll learn about the necessary dependencies and how to set up your test environment.

Write tests for Electron using TypeScript and mocha. The following tutorial will show you how to create a test setup.

Contents

Environment

Tested with:

  • Node.js v10.9.0
  • Electron v4.0.5

Code files

package.json
{
  "devDependencies": {
    "@babel/core": "7.3.3",
    "@babel/plugin-proposal-class-properties": "7.3.3",
    "@babel/preset-env": "7.3.1",
    "@babel/preset-typescript": "7.3.3",
    "@babel/register": "7.0.0",
    "@types/mocha": "5.2.6",
    "electron": "4.0.5",
    "electron-mocha": "6.0.4",
    "typescript": "3.3.3"
  },
  "main": "dist/main.js",
  "scripts": {
    "test": "electron-mocha --require ./babel-register.js src/**/*.test.ts"
  },
  "version": "0.0.0"
}
babel-register.js
require('@babel/register')({
  cache: false,
  extensions: ['.ts'],
  plugins: ['@babel/proposal-class-properties'],
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
    '@babel/preset-typescript',
  ],
});
tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "dist",
    "rootDir": "src",
    "target": "es5"
  },
  "exclude": ["dist", "node_modules"]
}

Takeaways

Checklist

  • --require ./babel-register.js must be used because you need to specify extensions for TypeScript and this cannot be done when using just --require @babel/register
  • @babel/preset-env is required with a node target because electron-mocha runs in a Node.js environment
  • @babel/preset-typescript is used to turn tests written in TypeScript into JavaScript: https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/
  • The @babel/proposal-class-properties is optional and only required if you code makes already use of class properties

Good to know

Back to Blog