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