为什么不叫我的茉莉花间谍? [英] Why is my jasmine spy not called?

查看:32
本文介绍了为什么不叫我的茉莉花间谍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently writing a unit test for Geolocation API.

我的 Angular 组件如下所示:

My Angular component looks as follow:

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

我的单元测试如下所示:

And my unit test looks like 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();
});

我的间谍没有被召唤,我不知道我做错了什么.enableNavigatorLocation 方法中通过 bind() 调用的函数会不会有问题?

My spy is not called and I have no idea what I am doing wrong. Could there be a problem with the function call via bind() in enableNavigatorLocation method?

我使用了这个帖子2012年作为指南

I used this post from 2012 as a guideline

推荐答案

发生这种情况是因为间谍活动出错了.

This happens because spying went wrong.

locationSuccesslocationError 间谍是局部变量.它们从不使用.callFake 中的参数具有相同名称这一事实不会影响任何事情.

locationSuccess and locationError spies are local variables. They are never used. The fact that params in callFake have same names doesn't affect anything.

正确的方法是存根navigator.geolocation.getCurrentPosition:

spyOn(navigator.geolocation, 'getCurrentPosition');

comp.enableNavigatorLocation();

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

这篇关于为什么不叫我的茉莉花间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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