Search code examples
jasminekarma-jasmine

How to access "jasmine" variable


I'm trying to mock the router. But more importantly I'm trying to access jasmine in my code. I'm running Karma v 6.3.20 and Jasmine 3.8. In my code, I need to use a Jasmine Spy.

I want to do something like jasmine.createSpy(...); but jasmine is undefined. How do I define the jasmine variable everyone references.

Example: https://angular.io/guide/testing-components-scenarios#routing-component

const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
const heroServiceSpy = jasmine.createSpyObj('HeroService', ['getHeroes']);

TestBed
    .configureTestingModule({
      providers: [
        {provide: HeroService, useValue: heroServiceSpy}, {provide: Router, useValue: routerSpy}
      ]
    })

I've tried to npm install --save-dev jasmine and then import jasmine from 'jasmine' but that doesn't even import. I get an error saying "Module jasmine can only be default-imported using the ‘allowSyntheticDefaultImports’ flag"


Solution

  • Make sure you have the packages @types/jasmine and jasmine installed and in tsconfig.spec.json, jasmine is specified in the types array under compilerOptions.

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

    Something else you can do is to generate an empty Angular project with the CLI and then go to the unit test file and see jasmine being available and try to copy its config. Files that should be looked are package.json, angular.json, tsconfig.json, test.ts, and tsconfig.spec.json.