/ angular

How to use Wallaby.js with Angular v5

Are you looking to use Wallaby.js with Angular? This article shows you how you can do exactly that. This allows us to visualise our unit test results on-screen inside of our editor. As always, I'll be using Visual Studio Code for this, but there are other options available.

Install the Wallaby.js Extension

The first step is to download the Wallaby.js extension from the extensions store. If you'd like to purchase a commercial version of Wallaby, I'd suggest looking at the pricing options on the webiste.

wallaby

Create a New Angular Project

Now that we've got the extension, we need to create a new Angular project using the CLI.

# Install the latest version of the Angular CLI
npm install @angular/cli -g

# Create a new Angular project
ng new NgWallaby

# Change directory
cd NgWallaby

# Install project dependencies
npm install wallaby-webpack angular2-template-loader --save-dev

# Open project inside of Visual Studio Code
code .

Configuration Files

In order to run Wallaby, we'll need to add the following configuration files:

  1. WallabyWebpack configuration file as seen from the NgCliWebpackSample project
var wallabyWebpack = require('wallaby-webpack');
var path = require('path');

var compilerOptions = Object.assign(
  require('./tsconfig.json').compilerOptions,
  require('./src/tsconfig.spec.json').compilerOptions);

module.exports = function (wallaby) {

  var webpackPostprocessor = wallabyWebpack({
    entryPatterns: [
      'src/wallabyTest.js',
      'src/**/*spec.js'
    ],

    module: {
      loaders: [
        {test: /\.css$/, loader: ['raw-loader', 'css-loader']},
        {test: /\.html$/, loader: 'raw-loader'},
        {test: /\.ts$/, loader: '@ngtools/webpack', include: /node_modules/, query: {tsConfigPath: 'tsconfig.json'}},
        {test: /\.js$/, loader: 'angular2-template-loader', exclude: /node_modules/},
        {test: /\.json$/, loader: 'json-loader'},
        {test: /\.styl$/, loaders: ['raw-loader', 'stylus-loader']},
        {test: /\.less$/, loaders: ['raw-loader', 'less-loader']},
        {test: /\.scss$|\.sass$/, loaders: ['raw-loader', 'sass-loader']},
        {test: /\.(jpg|png)$/, loader: 'url-loader?limit=128000'}
      ]
    },

    resolve: {
      extensions: ['.js', '.ts'],
      modules: [
        path.join(wallaby.projectCacheDir, 'src/app'),
        path.join(wallaby.projectCacheDir, 'src'),
        'node_modules'
      ]
    },
    node: {
      fs: 'empty',
      net: 'empty',
      tls: 'empty',
      dns: 'empty'
    }
  });

  return {
    files: [
      {pattern: 'src/**/*.+(ts|css|less|scss|sass|styl|html|json|svg)', load: false},
      {pattern: 'src/**/*.d.ts', ignore: true},
      {pattern: 'src/**/*spec.ts', ignore: true}
    ],

    tests: [
      {pattern: 'src/**/*spec.ts', load: false},
      {pattern: 'src/**/*e2e-spec.ts', ignore: true}
    ],

    testFramework: 'jasmine',

    compilers: {
      '**/*.ts': wallaby.compilers.typeScript(compilerOptions)
    },

    middleware: function (app, express) {
      var path = require('path');
      app.use('/favicon.ico', express.static(path.join(__dirname, 'src/favicon.ico')));
      app.use('/assets', express.static(path.join(__dirname, 'src/assets')));
    },

    env: {
      kind: 'chrome'
    },

    postprocessor: webpackPostprocessor,

    setup: function () {
      window.__moduleBundler.loadTests();
    },

    debug: true
  };
};

Next, we need to create a wallabyTest.ts file inside of our src folder. Once again, as seen from the NgCliWebpackSample project.

import './polyfills';

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

[1].forEach(() => 1 === 1)

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);

After this, we need to exclude the wallabyTest.ts file from our tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": ["node_modules/@types"],
    "lib": ["es2017", "dom"]
  },
  "exclude": ["wallabyTest.ts"]
}

Run Wallaby

The final step is to run Wallaby by pressing CMD + SHIFT + =. You may have to select a configuration file (wallaby.js), but otherwise select 'Start'.

testrun

Tada! Our test results are now available on screen. Green denotes a positive, passed test and red is a failed test. This saves us a tremendous amount of time as we're able to see any error messages inside of our editor.

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More