kodeaben
kodeaben

Reputation: 2065

mock declare const in jasmine test

I have a service in which I load a variable from a js file fetched from a CDN (read no typedef)

Therefore I have created a declaration for it:

declare const externalValue: string;

@Injectable() 
export class Service {
...

This is all very fine, but when I want to test my service, I get the following error message:

ReferenceError: externalValue is not defined

Which makes perfect sense since the index.html in which the file is loaded, has not been called.

My question is now how to mock this value when i test it?

Upvotes: 7

Views: 9315

Answers (2)

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

You can add the js files that need to be loaded in the browser when the test runs in karma.conf.js like this. Read more abpout karma configurations in their official documentation

files: [
   file1.js, // List of files/patterns to load in the browser.
   file2.js
]

or you can declare a global variable in the test file.

var externalValue = "externalValue";

describe('External value tests', () => {
    //
});

Upvotes: 1

Poul Kruijt
Poul Kruijt

Reputation: 71961

You can use the window object to make the value available:

window['externalValue'] = 'woww';

If you have your typescript on strict, you first have to extend the global window object. The global in this definition is not really necessary, but if you place it in a file which gets loaded for every file (like polyfills.ts), you only need to declare it once.

declare global { interface Window { externalValue: string; } }

Then you can do:

window.externalValue = 'even more wow';

Upvotes: 12

Related Questions