Ian Campbell
Ian Campbell

Reputation: 2748

Karma-Jasmine: Import Spy with noImplicitAny

If I set this in the tsconfig.json file of an Angular 4+ project:

"noImplicitAny": true,

...and import this to be used in a unit-test:

import { Spy } from "karma-jasmine";

...I am seeing this console error on npm test:

ERROR in C:/test-project/src/app/components/test/test.component.spec.ts (1,21):
Could not find a declaration file for module 'karma-jasmine'.
'C:/test-project/node_modules/karma-jasmine/lib/index.js' implicitly has an 'any' type.
Try `npm install @types/karma-jasmine` if it exists or add a new declaration (.d.ts) file containing `declare module 'karma-jasmine';`

I tried this:

  1. npm install --save-dev @types/karma-jasmine

  2. Add "types": [ "karma-jasmine" ] to tsconfig.json

...and am now seeing this console error on npm test:

ERROR in C:/test-project/src/app/components/test/test.component.spec.ts (1,21):
File 'C:/test-project/node_modules/@types/karma-jasmine/index.d.ts' is not a module.

How can I import Spy if "noImplicitAny": true is set?

If this is set to false (which is the default value), the import and usage works without error.

Example usage:

const testSpy: Spy = spyOn(testService, "test").and.callThrough();

Upvotes: 1

Views: 1014

Answers (1)

Estus Flask
Estus Flask

Reputation: 222309

That's because the name of the framework is Jasmine. Karma is test runner that shouldn't be mentioned in specs, and karma-jasmine is Karma plugin to seamlessly run Jasmine specs.

Since jasmine is a namespace, it should be:

import * as jasmine from "jasmine";

const spy: jasmine.Spy = ...;

jasmine is supposed to be global, and jasmine.Spy can be used directly without import.

Upvotes: 3

Related Questions