mardi 7 août 2018

Global scope Variable declared is not defined in test spec while testing using jasmine and karma

I have created an Injectable with a declaration for a global variable in the same file to be used. I am able to get it working in the code. But in my tests the declaration is failing with an undefined error.

declare var myGlobal;

@Injectable()
export class HttpService {
  constructor() {
    console.log(myGlobal);
  }
}

I am testing a component and this service is needed as a provider in the testbed for the component testing.

Following is how it is called:

    @Component({
    ...
    })
    export class AppComponent {
    constructor(_h: HttpService) {

    }
    ngOnInit(): void {
        this._h.fileUrl = window.location.href;
        this.getSettings(this._h.settingsSrc);
    }
}

Following is the declaration of the service in the test

beforeEach(async(() => {
    const settingsFile = 'json';
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        MenubarComponent,
      ],
      imports: [
        HttpClientModule,
      ],
      providers: [
        HttpService
      ],
    }).compileComponents();

it('getSettings() tests', inject([HttpService], async(async (_h: HttpService) => {
     const cmp = new AppComponent(_h);
     await cmp.ngOnInit(); // this is where the service function is trigered
}))

I have seen this Varaible declared is not defined in spec while testing but is not of help.

Aucun commentaire:

Enregistrer un commentaire