Angular里如何测试一个具有外部依赖的Component

时间:2022-07-25
本文章向大家介绍Angular里如何测试一个具有外部依赖的Component,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

例子:该Component依赖于UserService:

export class WelcomeComponent implements OnInit {
  welcome: string;
  constructor(private userService: UserService) { }

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

解决方案

在单元测试文件里,创建一个mock UserService:

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

Then provide and inject both the component and the service in the TestBed configuration.

把要测试的Component和UserService配置在providers数组里,Angular会自动完成依赖注入。

beforeEach(() => {
  TestBed.configureTestingModule({
    // provide the component-under-test and dependent service
    providers: [
      WelcomeComponent,
      { provide: UserService, useClass: MockUserService }
    ]
  });
  // inject both the component and the dependent service.
  comp = TestBed.inject(WelcomeComponent);
  userService = TestBed.inject(UserService);
});

Then exercise the component class, remembering to call the lifecycle hook methods as Angular does when running the app.

记得在单元测试代码里手动调用Component的lifecycle hook方法:

it('should welcome logged in user after Angular calls ngOnInit', () => {
  comp.ngOnInit();
  expect(comp.welcome).toContain(userService.user.name);
});