Angular 2 Unit Tests: Cannot find name 'describe'

I'm following this tutorial from angular.io

As they said, I've created hero.spec.ts file to create unit tests:

import { Hero } from './hero';
describe('Hero', () => {
  it('has name', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.name).toEqual('Super Cat');
  });
  it('has id', () => {
    let hero: Hero = {id: 1, name: 'Super Cat'};
    expect(hero.id).toEqual(1);
  });
});

Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:

Our editor and the compiler may complain that they don’t know what it and expect are because they lack the typing files that describe Jasmine. We can ignore those annoying complaints for now as they are harmless.

And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.

Example of what I get:

Cannot find name 'describe'.

Cannot find name 'it'.

Cannot find name 'expect'.

What can I do to fix it?


Solution 1:

I hope you've installed -

npm install --save-dev @types/jasmine

Then put following import at the top of the hero.spec.ts file -

import 'jasmine';

It should solve the problem.

Solution 2:

With [email protected] or later you can install types with:

npm install -D @types/jasmine

Then import the types automatically using the types option in tsconfig.json:

"types": ["jasmine"],

This solution does not require import {} from 'jasmine'; in each spec file.

Solution 3:

npm install @types/jasmine

As mentioned in some comments the "types": ["jasmine"] is not needed anymore, all @types packages are automatically included in compilation (since v2.1 I think).

In my opinion the easiest solution is to exclude the test files in your tsconfig.json like:

"exclude": [
    "node_modules",
    "**/*.spec.ts"
]

This works for me.

Further information in the official tsconfig docs.

Solution 4:

You need to install typings for jasmine. Assuming you are on a relatively recent version of typescript 2 you should be able to do:

npm install --save-dev @types/jasmine

Solution 5:

With [email protected] or later you can install types with npm install

npm install --save-dev @types/jasmine

then import the types automatically using the typeRoots option in tsconfig.json.

"typeRoots": [
      "node_modules/@types"
    ],

This solution does not require import {} from 'jasmine'; in each spec file.