Jasmine.js测试 - 窥探window.navigator.userAgent

时间:2017-10-18 08:49:24

标签: angular unit-testing jasmine karma-jasmine spyon

我需要找到改变userAgent值的方法。我尝试spyOn window.navigator.userAgent。但那没有帮助。

JS

@Injectable()
export class DetectBrowserService {
  browserIE: boolean;
  constructor() {
    this.browserIE = this.detectExplorer();
  }

  public detectExplorer() {
    const brows = window.navigator.userAgent;
    const msie = brows.indexOf('MSIE ');
    if (msie > 0) {
      // IE 10 or older => return version number
      return true;
    }
  }
}

规格

it('should test window.navigator.userAgent', () => {
  const wind = jasmine.createSpy('window.navigator.userAgent');
  wind.and.returnValue('1111');
  detectBrowserService = TestBed.get(DetectBrowserService);
  console.log(window.navigator.userAgent);
});

我期待1111,但获得了有关我浏览器的真实信息。

3 个答案:

答案 0 :(得分:9)

userAgentwindow.navigator上的只读/常量属性。 jasmine.createSpy通常用于在方法和NOT属性上创建间谍。

现在,我尝试直接执行window.navigator.userAgent = '1111';因为window.navigator只能在我的测试中访问。但我得到一个错误说:

  

[ts] Cannot assign to 'userAgent' because it is a constant or a read-only property. (property) NavigatorID.userAgent: string

enter image description here

所以唯一的选择是使用好的__defineGetter__。这就是我在这里所做的:

it('should test window.navigator.userAgent', () => {
  window.navigator['__defineGetter__']('userAgent', function(){
    return '1111' // Return whatever you want here
  });
  detectBrowserService = TestBed.get(DetectBrowserService);
  console.log(window.navigator.userAgent);
});

它有效: enter image description here

希望这有帮助!

答案 1 :(得分:1)

我意识到这很老了,但是为了扩展SiddAjmera的答案,这是我测试safari特定行为的方法。在测试结束时,它还会重置userAgent,以便不影响其他测试(如评论中的Pieter De Bie一样。)

it('should redirect if the user is on safari', () => {
  const originalUserAgent = navigator.userAgent;

  fixture = TestBed.createComponent(ComponentToTest);
  component = fixture.componentInstance;

  navigator['__defineGetter__']('userAgent', () => {
    return 'safari';
  });
  fixture.detectChanges();

  component.methodToTest();

  expect(component['window'].location.href).toBe('redirecturl.com');

  // unset the userAgent after test
  navigator['__defineGetter__']('userAgent', () => {
    return originalUserAgent;
  });
});

答案 2 :(得分:1)

我使用Jasmine API本身提供了一个简单的解决方案。

spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');

根据您的要求修改每个测试中的间谍。

不确定该API从哪个Jasmine版本存在,但v3.4支持此API