[Fixed] How to initialize a var defined in HTML in Angular unit test

Issue

I have a var declared in a component.ts file
declare var foo
this var is defined in index.html as <script>var foo = {}</script>

How can I mimic the declaration of index.html in Angular unit test

I am running a simple unit test to expect component to be truthy,
beforeEach(() => { fixture = TestBed.createComponent(FooComponent); component= fixture.componentInstance; fixture.detectChanges(); } it("should create", () => { expect(component).toBeTruthy; }) )

But I get the error ReferenceError: foo is not defined

Solution

make a script and add it to the angular.json

Your block should look similar to

 "test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    "main": "src/test.ts",    
    "polyfills": "src/polyfills.ts",
    "tsConfig": "tsconfig.spec.json",
    "karmaConfig": "karma.conf.js",
    "assets": ["src/favicon.ico", "src/assets"],
    "styles": ["src/assets/style/main.scss"],
    "scripts": [/* your script here */]
  }
},

Leave a Reply

(*) Required, Your email will not be published