Angular单元测试HostListener函数的条件Else部分。
创始人
2024-10-23 21:30:32
0

要在HostListener函数的条件Else部分运行单元测试,我们可以使用TestBed和ComponentFixture。首先,创建一个测试宿主组件,并在其中定义一个mock函数来测试条件Else部分。然后,使用TestBed创建组件实例,并使用ComponentFixture.detectChanges()触发变更检测周期。最后,使用spyOn()方法监听mock函数的调用。以下是示例代码:

组件:

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-cmp',
  template: `
Component
` }) export class MyComponent { @HostListener('window:resize', ['$event']) onResize(event) { if (event.target.innerWidth > 768) { console.log('Larger than 768px'); } else { this.onSmallerScreen(); } } onSmallerScreen() { console.log('Smaller than 768px'); } }

测试:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;
  let onSmallerScreenSpy: jasmine.Spy;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    onSmallerScreenSpy = spyOn(component, 'onSmallerScreen');
    fixture.detectChanges();
  });

  it('should call onSmallerScreen when window width is smaller than 768px', () => {
    const event = new Event('resize');
    Object.defineProperty(event.target, 'innerWidth', { writable: true, configurable: true, value: 500 });
    window.dispatchEvent(event);
    expect(onSmallerScreenSpy).toHaveBeenCalled();
  });

  it('should call console.log when window width is larger than 768px', () => {
    const event = new Event('resize');
    Object.defineProperty(event.target, 'innerWidth', { writable: true, configurable: true, value: 800 });
    window.dispatchEvent(event);

相关内容

热门资讯

重大发现!微扑克辅助神器,微扑... 重大发现!微扑克辅助神器,微扑克透牌(微扑克)其实是有挂(有挂详细)-哔哩哔哩;1、微扑克辅助神器系...
研究成果!微扑克ai会被检测到... 研究成果!微扑克ai会被检测到吗,微扑克有挂么(微扑克)本来是真的有挂(有挂解密)-哔哩哔哩亲,关键...
记者爆料!微扑克智能ai辅助,... 记者爆料!微扑克智能ai辅助,微扑克如何让系统发好牌(微扑克)本来存在有挂(有挂透视)-哔哩哔哩1、...
一分钟揭秘!微扑克辅助机器人,... 一分钟揭秘!微扑克辅助机器人,微扑克有挂么(微扑克)总是有挂(有挂功能)-哔哩哔哩1、微扑克辅助机器...
带你了解!微扑克如何让系统发好... 带你了解!微扑克如何让系统发好牌,微扑克有挂么(微扑克)本来是有挂(确实有挂)-哔哩哔哩1、构建自己...
玩家必看科普!微扑克系统发牌逻... 玩家必看科普!微扑克系统发牌逻辑,微扑克透牌(微扑克)确实有挂(有挂详情)-哔哩哔哩1、起透看视 微...
玩家必备教程!微扑克的辅助工具... 玩家必备教程!微扑克的辅助工具苹果,微扑克透牌(微扑克)真是是有挂(有挂存在)-哔哩哔哩;所有人都在...
一分钟揭秘!微扑克数据采集,微... 一分钟揭秘!微扑克数据采集,微扑克透牌(微扑克)果然是真的有挂(有挂细节)-哔哩哔哩1、进入到微扑克...
最新技巧!微扑克ai机器人,微... 最新技巧!微扑克ai机器人,微扑克ai机器人(微扑克)真是是有挂(有挂细节)-哔哩哔哩;1、微扑克a...
重大推荐!微扑克游戏辅助器,微... 重大推荐!微扑克游戏辅助器,微扑克如何让系统发好牌(微扑克)果然是有挂(有挂详情)-哔哩哔哩微扑克如...