Mock 'window' object in Jasmine + Angular

▼魔方 西西 提交于 2021-02-07 13:16:38

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/51949523/mock-window-object-in-jasmine-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!