Angular CLI单元测试扩展窗口方法

时间:2018-08-23 21:11:41

标签: angular unit-testing jasmine angular-cli

我正在尝试为Angular CLI(v6.0.8,带有@angular/core v6.0.9)组件编写单元测试,该组件调用通过服务注入的window对象上的方法,但是我遇到了一些问题。

以下是组件: MyComponent

import { WindowRefService} from '../../services/window-reference/window-reference.service'

export class MyComponent {

  constructor(private windowRef: WindowRefService) {}

  addAnother() {
    if ((this.windowRef.nativeWindow._thirdPartyWindowObject) {
      this.windowRef.nativeWindow._thirdPartyWindowObject.track("toolstart")
    }
  }
}

以下是服务:WindowRefService

import { Injectable } from '@angular/core'

export interface ICustomWindow extends Window {
  _thirdPartyWindowObject: {
    track: Function
  }
}

function getWindow (): any {
    return window
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): ICustomWindow {
        return getWindow()
    }
}

此服务是一种扩展Window类型的方法,以包括在应用程序加载页面的window对象中引入的第三方库。我知道这并不理想,但这是我所得到的用例。

这是我为addAnother方法编写的测试:

import { async, ComponentFixture, TestBed } from '@angular/core/testing'

import { MyComponent } from './MyComponent'
import { WindowRefService, ICustomWindow } from '../../services/window-reference/window-reference.service'

class WindowServiceMock {
  get nativeWindow (): ICustomWindow {
    return {
      ...window,
      _thirdPartyWindowObject: {
        track: (props: string) => {
          console.log('props', props)
          return true
        }
      }
    }
  }
}

describe('MyComponent', () => {
  let component: MyComponent
  let fixture: ComponentFixture<MyComponent>
  let windowSpy: WindowServiceMock

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          { provide: WindowRefService, useClass: WindowServiceMock }
        ]
      }
    })
    .compileComponents()
  }))

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent)
    component = fixture.componentInstance
    windowSpy = fixture.debugElement.injector.get(WindowRefService) as any
    fixture.detectChanges()
  })

  it('should call the third party scripts', () => {
    let spy = spyOn(windowSpy.nativeWindow._thirdPartyWindowObject, 'track')
    component.addAnother()
    expect(spy).toHaveBeenCalled()
  })
})

在我希望调用spy的{​​{1}}之前,一切都可以正常工作。当我检查日志时,可以看到windowSpy.nativeWindow._thirdPartyWindowObject.track内传递到toolstart内部的track方法中的WindowServiceMock字符串已注销,因此已调用存根服务 。但是,由于某种原因,间谍不是。

我确定我在这里遗漏了一些非常明显的东西,但是任何帮助都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

问题是 nativeWindow getter每次访问都会返回一个新对象。因此,您所侦听的函数与随后调用的函数不同。更新模拟程序的getter总是返回对同一 _thirdPartyWindowObject 对象的引用,因此,将返回相同的子函数,如下所示,该问题可以得到解决。不确定是否有更好的茉莉花方式来做到这一点。

const _thirdPartyWindowObject = {
  track: (props: string) => {
    console.log('props', props)
    return true
  }
}

class WindowServiceMock {
  get nativeWindow (): ICustomWindow {
    return {
      ...window,
      _thirdPartyWindowObject
    }
  }
}