235

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?

Community
  • 1
  • 1
Piotrek
  • 10,919
  • 18
  • 73
  • 136

17 Answers17

429

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
ksharifbd
  • 5,102
  • 2
  • 18
  • 23
  • If in Windows Powershell you have to do `npm install --save-dev "@types/jasmine"` (notice the double quotes) or will throw an error – aesede Feb 14 '17 at 13:20
  • 3
    Depending on the version of Typescript required you may need to install an earlier version. e.g For ionic v2.2.1 that I'm currently using that uses typescript v2.0.9, I needed to install `@types/jasmine@2.5.41`. Otherwise you may see [these compilation errors](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14569). – Tony O'Hagan Mar 17 '17 at 00:54
  • 19
    You could just import the module for its side effects: `import 'jasmine';` – cmolina May 30 '17 at 20:01
  • 8
    What does `import {} from 'jasmine';` actually do? Is it the same as `import 'jasmine'`? – TetraDev Sep 12 '17 at 18:50
  • I actually had similar problem with @types/jest, but it still applies – Dan Kuida Jan 23 '18 at 06:37
  • 2
    IN ANGULAR 6.0.3: I just imported "import {} from jasmine" and it worked again – Eduardo Cordeiro Jun 17 '18 at 18:49
  • It doesn't display 'describe, it, expect' in red error color, when 'import {} from 'jest';' but I am not supposed to put this expression, as it means nothing, as it does nothing (and there is no error on the console), but Webstorm continues displaying 'describe, it, expect' in red error color – getName Jul 24 '18 at 12:04
  • Turns out doing this once in one spec file removed 560 errors being shown in Visual Studio 2017 ... so ... thanks? :) – Arwin Sep 29 '18 at 09:30
  • 2
    @aesede What version of PS do you run? I just executed the command without any quotations marks and it went just well. – Konrad Viltersten Feb 27 '19 at 17:25
  • I dropped using Windows 2 years ago, so I can't say what version it was, but is possible the solution came from an update in npm – aesede Feb 27 '19 at 23:31
  • just `import 'jasmine';` will result in Error: Module not found: Error: Can't resolve 'jasmine'. `import {} from 'jasmine';` is the correct statement – Jacob Nelson Apr 11 '23 at 07:15
180

With Typescript@2.0 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.

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
Jiayi Hu
  • 2,210
  • 1
  • 14
  • 12
  • 10
    Per TypeScript docs for tsconfig.json (v2.1 at this time), its not necessary to add the `"types": ["jasmine"]` line anymore. "By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on." – bholben Feb 02 '17 at 04:46
  • 12
    @bholben I know, but for some reason `node` and `jasmine` types are not detected. At least it doesn't work for me and I'm using Typescript@2.1.5 – Jiayi Hu Feb 02 '17 at 12:19
  • 2
    This solution does not work for me :(, sorry. I used it in `ang-app/e2e/tsconfig.json`. _I tried it in every json level_. Could you please add more details? – Sergii Mar 03 '17 at 14:51
  • This would not work when using webpack - in this case the actual library needs to be served - the import {} from 'jasmine' pushes the library through – Bogdan Dec 05 '17 at 03:31
  • This worked for me, but I also had to upgrade my global typescript to 3.5.3 (from 2.5) – jsaddwater Aug 02 '19 at 12:27
  • @Sergii the tsconfig.json in the src folder – jsaddwater Aug 02 '19 at 12:30
  • This solution worked for me. However I had to add it the base `tsconfig.json` file. My project is created with angular/cli so it comes with few different tsconfig files one which is `tsconfig.spec.json` which has `"types": [ "jasmine" ]` already. But seems like it is not read. Instead I had to add that to the base tsconfig file. – starcorn Dec 02 '20 at 09:21
  • Additionally - if there is a tsconfig.json and others that extend from it - tsconfig.spec.json for tests. Then the types: array in the parent will override the types array in the children. So I deleted the types in the parent and set the test types I wanted in the child e.g. types: ["jasmine"] – Warren Jul 07 '21 at 23:50
28
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.

lenny
  • 2,978
  • 4
  • 23
  • 39
  • 4
    just a note: new Angular projects have `src/tsconfig.app.json`, `src/tsconfig.spec.json` and `tsconfig.json`. The mentioned "exclude" section is part of the 1st one. `"types": [ "jasmine" ]` part of the 2nd. – Martin Schneider Apr 13 '17 at 16:40
  • 2
    Note that in VS Code you lose the ability to find references in your spec files, as they will not be considered part of the Project. – mleu Jul 11 '17 at 15:01
  • @mleu I am facing the same problem. How did you fix this issue? Every time while writing the test case, I have to remove the spec files pattern from the `exclude` block. – Shishir Anshuman Mar 13 '18 at 17:50
  • @ShishirAnshuman: I did not find a solution and had to live with this limitation until the project ended. – mleu Mar 15 '18 at 08:27
  • 1
    @mleu Oh. No issue. In my project as a workaround, I removed the spec file pattern from the tsconfig's `exclude` block. Then I created a new `tsconfig.build.json` file with the spec file pattern added to the `exclude` block. Now, in my `ts-loader` options(in the webpack.config) I am using `tsconfig.build.json`. With these configurations, the modules are being resolved in the test files and while creating the build or starting the server, the test files are excluded. – Shishir Anshuman Mar 15 '18 at 08:34
  • Files included using "include" can be filtered using the "exclude" property. However, files included explicitly using the "files" property are always included regardless of "exclude". The "exclude" property defaults to excluding the node_modules, bower_components, jspm_packages and directories when not specified. You should add `"exclude": ["**/*.spec.ts"]` in the `tsconfig.app.json` file, not in the parent. – Christophe Chevalier Feb 13 '19 at 13:20
15

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
Liam
  • 27,717
  • 28
  • 128
  • 190
Pace
  • 41,875
  • 13
  • 113
  • 156
12

With Typescript@2.0 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.

mvermand
  • 5,829
  • 7
  • 48
  • 74
5

In order for TypeScript Compiler to use all visible Type Definitions during compilation, types option should be removed completely from compilerOptions field in tsconfig.json file.

This problem arises when there exists some types entries in compilerOptions field, where at the same time jest entry is missing.

So in order to fix the problem, compilerOptions field in your tscongfig.json should either include jest in types area or get rid of types comnpletely:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "types": ["reflect-metadata", "jest"],  //<--  add jest or remove completely
    "moduleResolution": "node",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
Omer Gurarslan
  • 979
  • 11
  • 15
3

Solution to this problem is connected with what @Pace has written in his answer. However, it doesn't explain everything so, if you don't mind, I'll write it by myself.

SOLUTION:

Adding this line:

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

at the beginning of hero.spec.ts file fixes problem. Path leads to typings folder (where all typings are stored).

To install typings you need to create typings.json file in root of your project with following content:

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160807145350"
  }
}

And run typings install (where typings is NPM package).

Community
  • 1
  • 1
Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • 4
    this is non-standard way of doing this. default tslint rules will prevent reference paths. use the tsconfig file to point to node_modules – FlavorScape May 03 '17 at 22:18
3

I'm up to the latest as of today and found the best way to resolve this is to do nothing...no typeRoots no types no exclude no include all the defaults seem to be working just fine. Actually it didn't work right for me until I removed them all. I had:

"exclude": [
    "node_modules"
]

but that's in the defaults so I removed that.

I had:

"types": [
    "node"
]

to get past some compiler warning. But now I removed that too.

The warning that shouldn't be is: error TS2304: Cannot find name 'AsyncIterable'. from node_modules\@types\graphql\subscription\subscribe.d.ts

which is very obnoxious so I did this in tsconfig so that it loads it:

"compilerOptions": {
    "target": "esnext",
}

since it's in the esnext set. I'm not using it directly so no worries here about compatibility just yet. Hope that doesn't burn me later.

Liam
  • 27,717
  • 28
  • 128
  • 190
philn5d
  • 636
  • 7
  • 12
  • You don't need to add `"types": ["node"]` in `tsconfig.json` but you should add this type in `tsconfig.app.json` ! You should don't have this warning again I think. You could keep `"target": "es5"` or `"target": "es6"` now. – Christophe Chevalier Feb 13 '19 at 13:27
3

In my case, the solution was to remove the typeRoots in my tsconfig.json.

As you can read in the TypeScript doc

If typeRoots is specified, only packages under typeRoots will be included.

moppag
  • 956
  • 9
  • 17
2

Only had to do the following to pick up @types in a Lerna Mono-repo where several node_modules exist.

npm install -D @types/jasmine

Then in each tsconfig.file of each module or app

"typeRoots": [
  "node_modules/@types",
  "../../node_modules/@types" <-- I added this line
],
Liam
  • 27,717
  • 28
  • 128
  • 190
SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on. See [official documentation](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) – Christophe Chevalier Feb 13 '19 at 13:15
2

I'll just add Answer for what works for me in "typescript": "3.2.4" I realized that jasmine in node_modules/@types there is a folder for ts3.1 under the jasmine type so here are the steps:-

  • Install type jasmine npm install -D @types/jasmine
  • Add to tsconfig.json jasmine/ts3.1

    "typeRoots": [ ... "./node_modules/jasmine/ts3.1" ],

  • Add Jasmine to the types

    "types": [ "jasmine", "node" ],

Note: No need for this import 'jasmine'; anymore.

Eslam Mahgoub
  • 164
  • 1
  • 5
1

In my case, I was getting this error when I serve the app, not when testing. I didn't realise I had a different configuration setting in my tsconfig.app.json file.

I previously had this:

{
  ...
  "include": [
    "src/**/*.ts"
  ]
}

It was including all my .spec.ts files when serving the app. I changed the include property toexclude` and added a regex to exclude all test files like this:

{
  ...
  "exclude": [
    "**/*.spec.ts",
    "**/__mocks__"
  ]
}

Now it works as expected.

King
  • 2,128
  • 1
  • 15
  • 15
1

I had this error in an angular library. Turns out I accidentally included my .spec file in the exports in my public-api.ts. Removing the export fixed my issue.

Jadamae77
  • 828
  • 7
  • 13
0

Look at the import maybe you have a cycle dependency, this was in my case the error, using import {} from 'jasmine'; will fix the errors in the console and make the code compilable but not removes the root of devil (in my case the cycle dependency).

G.Vitelli
  • 1,229
  • 9
  • 18
0

I'm on Angular 6, Typescript 2.7, and I'm using Jest framework to unit test. I had @types/jest installed and added on typeRoots inside tsconfig.json

But still have the display error below (i.e: on terminal there is no errors)

cannot find name describe

And adding the import :

import {} from 'jest'; // in my case or jasmine if you're using jasmine

doesn't technically do anything, so I thought, that there is an import somewhere causing this problem, then I found, that if delete the file

tsconfig.spec.json

in the src/ folder, solved the problem for me. As @types is imported before inside the rootTypes.

I recommend you to do same and delete this file, no needed config is inside. (ps: if you're in the same case as I am)

Kalamarico
  • 5,466
  • 22
  • 53
  • 70
getName
  • 693
  • 1
  • 9
  • 19
0

If the error is in the .specs file app/app.component.spec.ts(7,3): error TS2304: Cannot find name 'beforeEach'.

add this to the top of your file and npm install rxjs

import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
Pranav Singh
  • 17,079
  • 30
  • 77
  • 104
cfphpflex
  • 593
  • 5
  • 8
  • Why would installing and importing an unused function help solving typing issues? I doubt that this is really a valid answer – jlang Feb 09 '22 at 15:29
0

Just add to your tsconfig.json, and be sure that you don't have "**/*.spec.ts" in exclude

  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]

My working tsconfig.json enter image description here