Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Spec Helpers not loaded

I am trying to write my unit tests with Jasmine and Karma in a Typescript environment.

I have installed karma, karma-typescript, karma-jasmine, jasmine and jasmine-ts.

I have added a custom tsconfig.json to the spec directory and use it in the karma-typescript settings.

Generally, my tests are working, however, it doesn't execute my spec helpers.

Is there something I am missing for it to execute my spec helpers?


For your reference, here is my configuration:

karma.conf.js:

    module.exports = function (config) {
        config.set({
    
            // 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', "karma-typescript"],
    
    
            // list of files / patterns to load in the browser
            files: [
                "spec/helpers/chai.ts",
                {pattern: "src/**/*.ts"},
                {pattern: "spec/**/*.ts"}
            ],
    
    
            // 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: {
                "src/**/*.ts": ["karma-typescript"],
                "spec/**/*.ts": ["karma-typescript"]
            },
    
            karmaTypescriptConfig: {
                bundlerOptions: {
                    entrypoints: /\.spec\.ts$/
                },
                tsconfig: "./spec/tsconfig.json",
                coverageOptions: {
                    exclude: [/\.(d|spec|test)\.tsx?/, /\/spec\//]
                }
            },
            specReporter: {
                maxLogLines: 3,             // limit number of lines logged per test
                suppressErrorSummary: true, // do not print error summary
                suppressFailed: false,      // do not print information about failed tests
                suppressPassed: false,      // do not print information about passed tests
                suppressSkipped: true,      // do not print information about skipped tests
                showSpecTiming: false,      // print the time elapsed for each spec
                failFast: false              // test would finish with error when a first fail occurs.
            },
            // test results reporter to use
            // possible values: 'dots', 'progress'
            // available reporters: https://npmjs.org/browse/keyword/karma-reporter
            reporters: ['spec', "karma-typescript", "kjhtml"],
    
    
            // 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,
    
            // Concurrency level
            // how many browser should be started simultaneous
            concurrency: Infinity
        })
    }

jasmine.json (Although I have the feeling that it isn't used):

    {
      "spec_dir": "spec",
      "spec_files": [
        "**/*[sS]pec.ts"
      ],
      "helpers": [
        "helpers/**/*.ts"
      ],
      "stopSpecOnExpectationFailure": false,
      "random": false,
      "reporters": [
        {
          "name": "jasmine-spec-reporter#SpecReporter"
        }
      ],
      "project": "./spec/"
    }

tsconfig.json in root:

    {
      "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
          "es6",
          "dom",
          "es2015.promise"
        ],
        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        "outDir": "./dist/",
        "noImplicitAny": false,
        "allowJs": true,
        "baseUrl": "src",
        "typeRoots": [
          "node_modules/@types",
          "typings"
        ]
      },
      "include": [
        "src/**/*"
      ]
    }

tsconfig.json in spec folder:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "typeRoots": [
          "../node_modules/@types",
          "typings"
        ]
      },
      "include": [
        "./**/*",
        "../src/**/*"
      ]
    }

spec/helpers/chai.ts is the spec helper that karma is not executing.

The content of that file is:

import * as chai from "chai";
import chaiThings = require("chai-things");
import chaiInterface = require("chai-interface");

chai.should();
chai.use(chaiThings);
chai.use(chaiInterface);

Please see https://github.com/dhilgarth/mjt for a self contained example.

like image 472
Daniel Hilgarth Avatar asked Sep 15 '17 18:09

Daniel Hilgarth


2 Answers

So the problem here was that the Karma config had a minor mis-configuration that's easily missed.

The files node of the Karma config is completely valid and matches all the test specs you want Karma to load.

The karmaTypescriptConfig node of the karma config applies an extra filter on the files loaded by Karma, in your case you're only including files loaded by karma that match .spec.ts files.

The bundler couldn't find the helper specs as they didn't match the regex pattern: .spec.ts, even though they're specified under the files node. So the helper scripts were being excluded from the test after they'd been loaded.

The fix to this is to either remove the karmaTypescriptConfig node, reconfigure it to match the helper explicitly or rename the helper to be matched by the given matcher.

I've removed it from the below example. The bundler will bundle all files loaded by Karma by default.

The official documentation states

karmaTypescriptConfig.bundlerOptions.entrypoints - A regex filtering which files loaded by Karma should be executed in a test run, for example only filenames ending with ".spec.ts": /.spec.ts$/. This setting can be used to make sure the specs have finished setting up the test environment before other code starts requiring modules, which otherwise could lead to subtle bugs caused by race conditions. Defaults to all files, /.*/.

Hope this helps!

karma.conf.js:

module.exports = function (config) {
	config.set({

		// 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', "karma-typescript"],

		// list of files / patterns to load in the browser
		files: [
			"spec/helpers/helper.ts", {
				pattern: "src/**/*.ts"
			}, {
				pattern: "spec/**/*.ts"
			}
		],

		client: {
			clearContext: false // leave Jasmine Spec Runner output visible in browser
		},

		// 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: {
			"spec/helpers/helper.ts": ["karma-typescript"],
			"src/**/*.ts": ["karma-typescript"],
			"spec/**/*.ts": ["karma-typescript"]
		},

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

		// 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,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: Infinity
	})
}
like image 93
Daniel Lane Avatar answered Oct 27 '22 11:10

Daniel Lane


At the moment the only viable options is to store helpers in separate forlder, compile them with tsc and add as .js files to karma.config

Check this PR for steps to make it work: https://github.com/dhilgarth/mjt/pull/1/files

    files: [
        {pattern: "spec/helpers/*.js"},
        {pattern: "src/**/*.ts"},
        {pattern: "spec/**/*.ts"}
    ],

    client:{
      jasmine: {
        helpers: [
          "spec/helpers/*.js"
        ]
      }
    },
like image 24
valorkin Avatar answered Oct 27 '22 11:10

valorkin