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.
Join the DZone community and get the full member experience.
Join For FreeIn 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$/);
Opinions expressed by DZone contributors are their own.
Comments