Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock 'window' object in Jasmine + Angular

I have a function which I want to unit-test and into it I am comparing global objects window & parent as const isEqual = (window === parent);

Which is the best way how to mock those objects in Angular/TypeScript?

One more idea is to get those objects through function parameters, but anyway it's not solving this problem because I need to mock global window object too if I am using getSomeData(win: Window, parent: Window) { // ... }

like image 291
Toms Tumshais Avatar asked Aug 21 '18 13:08

Toms Tumshais


1 Answers

I went with this solution:

Create service which will inject window object.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class GlobalObjectService {
  public getWindow(): Window {
    return window;
  }
}

And in tests it's looks like:

describe('TestService', () => {
  ...
  let globalObjectService: jasmine.SpyObj<GlobalObjectService>;

  beforeEach(() => {
    globalObjectService = jasmine.createSpyObj('GlobalObjectService', ['getWindow']);
    ...
  });

  describe('#testFunc', () => {
    it('should test something', () => {
      globalObjectService.getWindow.and.returnValue({
        location: {
          href: 'window.location.href',
        },
      });
      ...
    });
  });
});
like image 169
Toms Tumshais Avatar answered Oct 04 '22 20:10

Toms Tumshais