Angular里如何测试一个具有外部依赖的Component
生活随笔
收集整理的這篇文章主要介紹了
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 serviceproviders: [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); });總結
以上是生活随笔為你收集整理的Angular里如何测试一个具有外部依赖的Component的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular单元测试框架karma-j
- 下一篇: SAP Spartacus基于travi