在Jasmine + Angular中模拟“窗口"对象 [英] Mock 'window' object in Jasmine + Angular

查看:79
本文介绍了在Jasmine + Angular中模拟“窗口"对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要进行单元测试的功能,我正在其中比较全局对象window& parent as const isEqual = (window === parent);

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);

哪种方法是在Angular/TypeScript中模拟那些对象的最佳方法?

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

另一个想法是通过函数参数获取那些对象,但是无论如何它都不能解决这个问题,因为如果使用getSomeData(win: Window, parent: Window) { // ... }

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

推荐答案

我接受了以下解决方案:

I went with this solution:

创建将注入window对象的服务.

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

这篇关于在Jasmine + Angular中模拟“窗口"对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆