Galdor
Galdor

Reputation: 1955

Namespace jasmine not found in /node_modules/angular2/src/testing/matchers.d.ts

I want to test my angular2 app with karma, but I get a typescript error:

/my/path/node_modules/angular2/src/testing/matchers.d.ts

Error:(4, 37) TS2503: Cannot find namespace 'jasmine'.

NPM Modules are installed, typescript compiler is running well. What's wrong?

myservice.serviceSpec.ts:

import {it, describe, expect, beforeEach, inject} from 
'angular2/testing';
import {myService} from "../app/myservice.service";

describe('Tests', () => {
    it('should be true', () => {
        expect(true).toBe(true);
    });
});

package.json:

{
  "name": "myapp",
  "version": "0.1.0",
  "dependencies": {
    "angular2": "^2.0.0-beta.2",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.13",
    "reflect-metadata": "^0.1.2",
    "rxjs": "^5.0.0-beta.0",
    "systemjs": "^0.19.17",
    "zone.js": "^0.5.10"
  },
  "devDependencies": {
    "jasmine-core": "^2.4.1",
    "karma": "^0.13.19",
    "karma-chrome-launcher": "^0.2.2",
    "karma-coverage": "^0.5.3",
    "karma-jasmine": "^0.3.7",
    "remap-istanbul": "^0.5.1"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true
  },
  "exclude": [
    "node_modules"
  ]
}

karma.conf.js:

// Karma configuration
// Generated on Wed Feb 10 2016 09:56:19 GMT+0100 (CET)

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'],


        // list of files / patterns to load in the browser
        files: [
            'node_modules/systemjs/dist/system.src.js',
            'node_modules/angular2/bundles/http.dev.js',
            'test/karma_test_shim.js',
            'test/myservice.serviceSpec.js',
            {pattern: 'app/**/*.js', included: false, watched: true},
            {pattern: 'test/**/*Spec.js', included: false, watched: true}
        ],


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


        // 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
    })
}

karma_test-shim.js:

// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
  packages: {
    'base/app': {
      defaultExtension: false,
      format: 'register',
      map: Object.keys(window.__karma__.files).
            filter(onlyAppFiles).
            reduce(function createPathRecords(pathsMapping, appPath) {
              // creates local module name mapping to global path with karma's fingerprint in path, e.g.:
              // './hero.service': '/base/src/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
              var moduleName = appPath.replace(/^\/base\/app\//, './').replace(/\.js$/, '');
              pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
              return pathsMapping;
            }, {})
    }
  }
});
System.import('angular2/testing').then(function(testing) {
  return System.import('angular2/platform/testing/browser').then(function(testing_platform_browser) {
    testing.setBaseTestProviders(testing_platform_browser.TEST_BROWSER_PLATFORM_PROVIDERS,
                                 testing_platform_browser.TEST_BROWSER_APPLICATION_PROVIDERS);
  });
}).then(function() {
  return Promise.all(
    Object.keys(window.__karma__.files) // All files served by Karma.
    .filter(onlySpecFiles)
    .map(function(moduleName) {
      // loads all spec files via their global module names
      return System.import(moduleName);
  }));
}).then(function() {
  __karma__.start();
}, function(error) {
  __karma__.error(error.stack || error);
});
function onlyAppFiles(filePath) {
  return /^\/base\/app\/.*\.js$/.test(filePath)
}
function onlySpecFiles(path) {
  return /Spec\.js$/.test(path);
}

Upvotes: 7

Views: 10461

Answers (6)

Serhii
Serhii

Reputation: 7543

The similar issue in my case was resolved using import:

import * as jasmine from 'jasmine-core';

P.S. Make sure the first you have installed necessary jasmine packages (jasmine-core ...).

Upvotes: 1

Dila Gurung
Dila Gurung

Reputation: 1764

In my case installing "@types/jasmine" fixed this issue.

Upvotes: 3

ramon22
ramon22

Reputation: 3618

You can try declaring jasmine

namespace Tests {
  declare var jasmine
  ///tests
  describe('Tests', () => {
      it('should be true', () => {});
  });
}

Upvotes: 1

MrLehiste
MrLehiste

Reputation: 1036

Just run following command in your project root folder:

typings install jasmine --save-dev --ambient

Then reference paths are not longer necessary

Upvotes: 2

Galdor
Galdor

Reputation: 1955

Answer is in angular2 upgrade guide:

Add a file called test_helper.ts to the test directory and add a reference to the Jasmine and mock type definitions we already installed earlier: test/test_helper.ts

/// <reference path="../typings/jasmine/jasmine.d.ts" />

Upvotes: 1

MatthewScarpino
MatthewScarpino

Reputation: 5936

The compiler needs the Jasmine declaration file, jasmine.d.ts, to declare Jasmine's functions. You can download it from here and reference it in TypeScript with:

/// <reference path="jasmine.d.ts"/>

Upvotes: 5

Related Questions