Jasmine Unit testing define library that was imported as a global variable

1.6k Views Asked by At

I have a project that uses pdfMake to generate a PDF. To use it I include the file in my index.html

<script src='js/pdfmake.js'></script>
<script src='js/vfs_fonts.js'></script>

Inside pdfmake.js it declares global["pdfMake"] which then allows me to use the library in my service.

pdfService:

pdfMake.createPdf(docDefinition).download(fileName);

Everything works great but when I tried to test ths method in my service I get an error that the test can't find the variable pdfMake. That makes sense considering it's loaded by index.html.

How can I replace this library with a mock in my test?

I've tried using a spy but since makePdf isn't a function that doesn't work. spyOn(service, 'makePdf').

I tried just setting it as a variable but that also didn't work and I get: Strict mode forbids implicit creation of global property 'pdfMake'

pdfMake = {
  createPdf: jasmine.createSpy('createPdf').and.returnValue({
    download: jasmine.createSpy('download')
  }
}
2

There are 2 best solutions below

0
On

I just fixed this issue by making below changes-

Declare pdfMake variable globally in your .ts file like-

declare var pdfMake;

And then mock the pdfMake function in your .spec file like this-

window['pdfMake'] = {
createPdf: function (param) {
  return {
    open: function () {
      return true;
    },
    download: function () {
      return true;
    }
  };
}

};

0
On

I got the same problem and solved inserting the pdfMake mock on global variable window inside the unit test. So, in your case will be something like this:

window.pdfMake = {
  createPdf: jasmine.createSpy('createPdf')
  .and.returnValue({
    download: jasmine.createSpy('download')
  }),
};