Toms Tumshais
Toms Tumshais

Reputation: 353

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) { // ... }

Upvotes: 7

Views: 10808

Answers (1)

Toms Tumshais
Toms Tumshais

Reputation: 353

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',
        },
      });
      ...
    });
  });
});

Upvotes: 5

Related Questions