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');
});