Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
methgaard Avatar asked Jul 10 '18 06:07

methgaard


Video Answer


2 Answers

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';
like image 90
Poul Kruijt Avatar answered Oct 01 '22 00:10

Poul Kruijt


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', () => {
    //
});
like image 35
Anuradha Gunasekara Avatar answered Sep 30 '22 23:09

Anuradha Gunasekara