Search code examples
angularkarma-jasminekarma-runnerkarma-webpack

How to test in Karma without require.context


So I spent a long time in React land, with Jest as my test runner/environment. Flash forward to new job, and we're unit testing an Angular 8 app w/ Karma.

Much to my dismay, I come to find the default config for Angular, and every single guide out there suggests something close to this line:

const context = require.context('../src/app', true, /\.spec\.ts$/);

So when I update a file within my app, Angular CLI/Webpack have to rebuild whatever, and then it re-executes my entire f-ing test suite, which is thousands of tests, again.

I'm looking around and I see that Karma understands the concept of finding and watching files, but it seems as if that would never work given this approach.

Problem is we need to run this code to setup the environment:

import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';
import 'core-js/proposals/reflect-metadata';

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

declare const require: any;

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

Anybody have differential file watching / test running in Angular w/ Karma? If so, how it do???

Is there an easy way to run this setup code similar to Jest's setupFilesAfterEnv?

Relevant Karma config (I don't use NG CLI, test.ts has the content above):

    frameworks: ['parallel', 'jasmine'],

    plugins: [
      require('ts-loader'),
      require('karma-jasmine'),
      require('karma-webpack'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-spec-reporter'),
      require('karma-parallel'),
    ],

    files: [{ pattern: './test/index.ts', watched: false }],

    preprocessors: {
      './test/index.ts': ['webpack'],
    },
    webpack: karmaConfig(),

    webpackMiddleware: {
      stats: 'errors-warnings',
    }

Solution

  • You have three solutions here I think:

    1) Use Jest instead for Angular testing (It's possible!)

    2) Use WallabyJS which can run behind the scenes and only execute changed tests. We use this and it's excellent.

    3) Use fdescribe and fit to precisely target tests