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?
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';
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', () => {
//
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With