Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Running a Karma Test Case for a Single Spec File / Single module

DZone's Guide to

Running a Karma Test Case for a Single Spec File / Single module

This quick tutorial shows how to run unit test cases on a single spec file when using Karma and Jasmine for your Angular unit tests.

Free Resource

Sensu is an open source monitoring event pipeline. Try it today.

In this article, I'll explain the steps to run unit test cases for a single spec file and help developers complete Angular unit tests fast. There are many approaches to running Angular unit test cases for a single file, but I will explain the simplest one, which won't affect the code coverage for other team members' unit test cases. 

Step 1

Add the Spec name in the test.ts file under the src folder. 

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

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /Test-Demo\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

Note: Test-Demo is nothing but Test-Demo.spec.ts.

Step 2

Run ng test --code-coverage 

Now Karma and Jasmine will check only Test-Demo.Spec.ts.

Before you push, you should run all the test cases and don’t push this file to the next repository.

Hope you enjoy. 


Step 3

Run Karma on module base 

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

Sensu: workflow automation for monitoring. Learn more—download the whitepaper.

Topics:
angular ,jasmine ,karma ,unit testing ,tutorial ,performance

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}