Angular 组件类测试

本文介绍了如何测试Angular组件,包括没有依赖的组件和有依赖的组件。通过new关键字创建组件,使用toBe和toMatch等matchers进行断言,测试@Input和@Output属性,并详细讲解了TestBed在处理有依赖组件测试中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Angular测试组件的基础知识之一是 “测试组件类”。

测试没有依赖的组件类

测试没有依赖的组件类,需要遵循与没有依赖的服务相同的步骤:

  • 使用 new 关键字创建一个组件。
  • 调用它的 API。
  • 对其公开状态的期望值进行断言。
// 没有依赖的组件类
@Component({
  selector: 'lightswitch-comp',
  template: `
    <button (click)="clicked()">Click me!</button>
    <span>{{message}}</span>`
})
export class LightswitchComponent {
  isOn = false;
  clicked() { this.isOn = !this.isOn; }
  get message() { return `The light is ${this.isOn ? 'On' : 'Off'}`; }
}
// 测试
describe('LightswitchComp', () => {
  it('#clicked() should toggle #isOn', () => {
    const comp = new LightswitchComponent();
    expect(comp.isOn).toBe(false, 'off at first');
    comp.clicked();
    expect(comp.isOn).toBe(true, 'on after click');
    comp.clicked();
    expect(comp.isOn).toBe(false, 'off after second click');
  });

  it('#clicked() should set #message to "is on"', () => {
    const comp = new LightswitchComponent();
    expect(comp.message).toMatch(/is off/i, 'off at first'); // 正则匹配 i:大小写不敏感。
    comp.clicked();
    expect(comp.message).toMatch(/is on/i, 'on after clicked');
  });
});

知识点:toBe、toMatch、更多matchers

toBe:期望实际值 === 期望值。
toMatch:期望实际值与正则表达式匹配。
更多matchers:https://jasmine.github.io/api/edge/matchers.html

测试 @Input 和 @Output

export class DashboardHeroComponent {
  @Input() hero!: Hero;
  @Output() selected = new EventEmitter<Hero>();
  click() { this.selected.emit(this.hero); }
}
// 测试
it('raises the selected event when clicked', () => {
  const comp = new DashboardHeroComponent();
  const hero: Hero = {id: 42, name: 'Test'};
  comp.hero = hero;

  // 订阅自定义事件selected发出的值
  comp.selected.pipe(first()).subscribe((selectedHero: Hero) => { 
      // 验证有触发selected事件,验证emit出来的值
      expect(selectedHero).toBe(hero)
  });
  
  // 触发selected自定义事件发出值
  comp.click();
});

测试有依赖的组件类 TestBed

// 有依赖的组件类
export class WelcomeComponent implements OnInit {
  welcome = '';
  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.welcome = this.userService.isLoggedIn ?
      'Welcome, ' + this.userService.user.name : 'Please log in.';
  }
}

class MockUserService {
  isLoggedIn = true;
  user = { name: 'Test User'};
}

当组件有依赖时,使用 TestBed 来同时创建[提供(provide)注入(inject)]该组件及其依赖。
TestBed:配置和初始化用于单元测试的环境,并提供用于在单元测试中创建组件和服务的方法。

// 在 TestBed 配置中【提供】并【注入】所有所需的组件和服务
beforeEach(() => {
  TestBed.configureTestingModule({
    // 提供(provide)组件和所依赖的服务
    providers: [
      WelcomeComponent,
      { provide: UserService, useClass: MockUserService }
    ]
  });
  // 注入(inject)组件和所依赖的服务
  comp = TestBed.inject(WelcomeComponent);
  userService = TestBed.inject(UserService);
});


// 开始测试
it('should not have welcome message after construction', () => {
  expect(comp.welcome).toBe('');
});

it('should welcome logged in user after Angular calls ngOnInit', () => {
  comp.ngOnInit(); // 别忘了要像 Angular 运行应用时一样调用生命周期钩子方法
  expect(comp.welcome).toContain(userService.user.name);
});

it('should ask user to log in if not logged in after ngOnInit', () => {
  userService.isLoggedIn = false;
  comp.ngOnInit();
  expect(comp.welcome).not.toContain(userService.user.name);
  expect(comp.welcome).toContain('log in');
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值