例子:該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);
});