Write Typescript UT with Karma & Jasmine


What is Karma


Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。这个测试工具的一个强大特性就是,它可以监控(Watch)文件的变化,然后自行执行,通过console.log显示测试结果。

Install Karma

Using below commands to install Karma with npm

npm install -g karma
npm install -g karma-cli
npm install karma-jasmine karma-chrome-launcher [optional]

Karma Config


  • basePath
  • frameworks
  • files
  • excludes
  • port
  • browsers


// Karma configuration
// Generated on Fri Aug 14 2015 14:42:50 GMT-0400 (Eastern Daylight Time)

module.exports = function (config) {
        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', 'requirejs'],

        // list of files / patterns to load in the browser
        files: [
          { pattern: 'Web/src/**/*.js', included: false },
          { pattern: 'Web/src/**/*.html', included: false },
          { pattern: 'Web/tests/**/*.test.js', included: false },

        // list of files to exclude
        exclude: [

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false


test-main.js is the entrance of the test run.


var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function (file) {
    if (TEST_REGEXP.test(file)) {
        // Normalize paths to RequireJS module names.
        // If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
        // then do not normalize the paths
        var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');

    // Karma serves files under /base, which is the basePath from your config file
    baseUrl: '/base',

    paths: {
        'angular': 'http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min',
        'angularMocks': 'http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-mocks',
        text: 'http://cdnjs.cloudflare.com/ajax/libs/require-text/2.0.12/text.min',
        'lodash': 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min',

    shim: {
        'angular': { exports: 'angular' },
        'angularMocks': { deps: ['angular'] }

    // dynamically load all test files
    deps: allTestFiles,

    // we have to kickoff jasmine, as it is asynchronous
    callback: window.__karma__.start

Write Typescript UT

1. Create module

var mockedModule = angular.module("mock.module", []);

Create module with $provide

var mockedModule = module('mock.module', ($provide) => {
        //register mocked services/values to module runtime
        $provide.value('$translate', mockedTranslate);

2. Register filter/controller to module

mockedModule.filter(targetFilter.name, targetFilter.filterClass);

3. Apply module


4. Inject the filter/scope/controller or other resources

var fieldFilter
inject(($filter) => {
    fieldFilter = $filter(targetFilter.name);

or use new keyword to create an instance, this can skip the step 1,2 and 3

fieldFilter = new targetModule.filterClass(scope, mockedDataService, mockedBusinessService);

5. Write Cases

it("Should be able to convert number to eggs", () => {
    expect(fieldFilter(1)).toEqual("1 egg");
    expect(fieldFilter(2)).toEqual("2 eggs");

Run UT

At the root folder of the source code, for example,


Run the below command:

karma start

You will see the test result:


Click the “Debug” button on the page to enter debug mode



  • It will run UT automatically when it detected file changes
  • Terminates it press Crtl + C


Karma Introduction

0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments