为什么我的茉莉花间谍没有被召唤?

时间:2017-05-24 09:48:27

标签: javascript angular unit-testing typescript jasmine

我目前正在为Geolocation API编写单元测试。

My Angular组件如下所示:

export class HeaderComponent {
  public lat: number = 56.713;
  public lng: number = 21.1644;
  public message: string;
  public messageType: string;

  public locationSuccess(data: any) {
    console.log(data);
    if (data) {
      if (data.coords) {
        this.lat = data.coords.latitude ? data.coords.latitude : this.lat;
        this.lng = data.coords.longitude ? data.coords.longitude : this.lng;
        this.messageType = 'success';
        this.message = 'You successfully granted us retrieving your location to ' +
                       'enhance your experience.';
      }
    }
  }

  public locationError() {
    console.log('error');
    this.message = 'Unfortunately we could not acquire your location which is recommended ' +
                   'for best user experience with our service.';
    this.messageType = 'danger';
  }

  public enableNavigatorLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        this.locationSuccess.bind(this),
        this.locationError.bind(this)
      );
    }
  }
}

我的单元测试看起来像这样:

// synchronous beforeEach
beforeEach(() => {
  fixture = TestBed.createComponent(HeaderComponent);
  comp = fixture.componentInstance;
});

it('enableNavigatorLocation should call locationSuccess if successful', () => {
  const locationSuccess = jasmine.createSpy('locationSuccess');
  const locationError = jasmine.createSpy('locationError');

  spyOn(navigator.geolocation,'getCurrentPosition').and.callFake(function(locationSuccess, locationError) {
    const position = { coords: { latitude: 32, longitude: -96 } };
    arguments[0](position);
  });

  comp.enableNavigatorLocation();

  expect(locationSuccess).toHaveBeenCalled();
});

我的间谍没有打电话,我不知道我做错了什么。在bind()方法中通过enableNavigatorLocation调用函数会出现问题吗?

我在2012年使用此post作为指南

1 个答案:

答案 0 :(得分:1)

这是因为间谍出错了。

locationSuccesslocationError间谍是局部变量。他们从未使用过。 callFake中的params具有相同名称的事实不会影响任何事情。

执行此操作的正确方法是存根navigator.geolocation.getCurrentPosition

spyOn(navigator.geolocation, 'getCurrentPosition');

comp.enableNavigatorLocation();

expect(navigator.geolocation.getCurrentPosition).toHaveBeenCalledWith(
  comp.locationSuccess,
  comp.locationError
);