【问题标题】:jasmine spy on window.innerwidth not getting called茉莉花间谍 window.innerwidth 没有被调用
【发布时间】:2021-02-18 16:26:04
【问题描述】:

在我的 Angular 7 项目中,我想模拟 window.innerWidth 以根据测试用例返回一个特定的值,但它最终调用了实际的 window.innerWidth,这是运行 karma 的屏幕宽度。

Component.spec.ts:

it(`view on small screen`, () => {
  spyOnProperty(window, 'innerWidth', 'get').and.returnValue(1900);
  component.adjustLayout();
});

组件.ts:

adjustLayout() {
   const width = window.innerWidth;
  ...
}

软件包版本:

"@types/jasmine": "2.8.3",
"jasmine-core": "2.8.0",
"karma-jasmine": "1.1.0",

【问题讨论】:

标签: angular jasmine karma-jasmine


【解决方案1】:

对于更改窗口大小然后进行断言,我发现使用 this (karma-viewport) npm 包是最好的,您可以在其中指定视口的宽度和高度。

viewport.set(1900);
component.adjustLayout();

【讨论】:

    【解决方案2】:

    最好的方法是通过注入令牌提供window。 但如果不可能,您可以使用ng-mocks 来提供可以被窥探的正确属性定义。

    带有解决方案的沙盒:https://codesandbox.io/s/goofy-sunset-uq8lt?file=/src/test.spec.ts

    describe('SomeComponent', () => {
      // keep SomeComponent and mocks MatTabsModule
      beforeEach(() => MockBuilder(SomeComponent));
    
      fit(`view on small screen`, () => {
        const component = MockRender(SomeComponent).point.componentInstance;
    
        // after that we can spy it
        ngMocks.stub(window, 'innerWidth', 'get');
    
        spyOnProperty(window, 'innerWidth', 'get').and.returnValue(1900);
    
        component.adjustLayout();
        expect(component.width).toEqual(1900);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2014-01-25
      • 2012-08-15
      • 1970-01-01
      相关资源
      最近更新 更多