angular - Jasmine.js 测试 - 监视 window.navigator.userAgent

标签 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,但得到了关于我的浏览器的真实信息。

最佳答案

我使用 Jasmine api 本身得到了一个简单的解决方案。

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

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

不确定这个 API 从哪个 Jasmine 版本开始出现,但是 v3.4 支持这个 API

一旦您侦测到任何全局属性,最好清除该侦测afterEach 测试。

例如。

describe('Test', function() {
  const NAVIGATOR = window.navigator;

  beforeEach(function() {
    spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
  })

  afterEach(function() {
    window.navigator = NAVIGATOR;
  });
}

关于angular - Jasmine.js 测试 - 监视 window.navigator.userAgent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806185/

相关文章:

javascript - 无法通过 Angular 管道搜索对象数组值

unit-testing - 在 Laravel 中单元测试 Controller 而不测试路由的最佳方法是什么

javascript - 引用错误 : Can't find variable: require at

angular - 错误 : Cannot reattach ActivatedRouteSnapshot created from a different route

javascript - Angular : sanitizing HTML stripped some content on css style

unit-testing - 关于单元测试库/框架的最佳实践是什么?

ruby-on-rails - 具有存储库模式的 Ruby on Rails?

angularjs - 等待 Protractor 与页面同步时出错 : "[ng:test] no injector found for element argument to getTestability

iphone - 在 iPhone 开发中使用 Jasmine?

javascript - Ionic 2 中的导航栏和标题内滑动