【问题标题】:Mock window object in Jasmine unit test caseJasmine 单元测试用例中的模拟窗口对象
【发布时间】:2021-03-31 04:23:02
【问题描述】:

我正在尝试编写一个测试用例,但由于无法在 jasmine 的单元测试用例中复制窗口,所以我被卡住了。

我有一堂课如下

 public init(): void {
    this.Icon['text'] = window['SWIPE']['src'];
    this.Icon['altTag'] = window['SWIPE']['alt'];
  }

我尝试在 spec.ts 文件中模拟上述窗口对象,如下所示

 let window = {
      'SWIPE': { 'src': 'image', alt: 'image' }
    };

init类是根据条件从其他类中调用出来的,如下

 public onMessageReceived(event: object) {
        switch (event && event['event']) {
          case 'onNavigation':
            this.init();
            this.isReady = true; 
            break;
    }
    }

我写的测试用例如下

it('should set isReady as true on onNavigation value in switch', async(() => {
    component.ngOnInit();
    fixture.detectChanges();

    fixture.whenStable().then(() => {
      component.onMessageReceived({ event: 'onNavigation', data: {} });
      expect(component.isReady).toBeTrue();
    });
  }));

我在 beforeEach 中尝试和模拟的窗口的值如下

beforeEach(() => {
    fixture = TestBed.createComponent(ConComponent);
    component = fixture.componentInstance;


    let window = {
      'SWIPE': { 'src': 'image', alt: 'image' }
    };


    fixture.detectChanges();
  });

当我运行测试用例时,我得到一个错误“TypeError: Cannot read property 'src' of undefined”我哪里会出错任何指导都会有帮助,因为我还在学习用 jasmine 编写测试用例

【问题讨论】:

  • let window 声明了一个名为 window 的 local 变量,它不会被任何引用 global 的东西看到窗户。一个简单的解决方案是拥有一个包装全局窗口的 service,这是你的代码的其余部分可以使用的外观,然后注入它的测试替身进行测试。
  • 您能否提供一个与您@jonrsharpe 相同的请求的示例

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


【解决方案1】:

一个可能的选择是存根 window 对象进行测试

// backup / restore the property.
const backup = window.SWIPE;
beforeEach(() => backup = window.SWIPE);
afterEach(() => window.SWIPE = backup);

// now the test
beforeEach(() => {
  // no let of const
  window = {
    'SWIPE': { 'src': 'image', alt: 'image' }
  };

  fixture = TestBed.createComponent(ConComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

PS。正确的方法是重构应用程序以提供window 作为令牌。然后你可能会通过providers 伪造它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多