【发布时间】:2018-06-20 11:40:22
【问题描述】:
您好,感谢您抽出宝贵时间!
我正在学习如何使用 Angular,并且我有兴趣学习如何测试其组件。
目前我正在苦苦挣扎,因为我已经完成了 Angular 页面的英雄之旅教程,并且我正在测试代码以更好地理解它。
关键是我正在测试 hero-details 组件的代码是:
import {Component, OnInit, Input} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {MyHeroService} from '../hero-service/my-hero.service';
import {Location} from '@angular/common';
import {Hero} from '../Hero';
@Component({
selector: 'app-hero-details',
templateUrl: './hero-details.component.html',
styleUrls: ['./hero-details.component.css']
})
export class HeroDetailsComponent implements OnInit {
@Input() hero: Hero;
constructor(private route: ActivatedRoute,
private myHeroService: MyHeroService,
private location: Location) {
}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.myHeroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
}
我的测试试图证明 getHero() 在创建 hero-details 组件后被调用:
import {HeroDetailsComponent} from './hero-details.component';
import {ActivatedRoute} from '@angular/router';
import {MyHeroService} from '../hero-service/my-hero.service';
import {MessageService} from '../message.service';
import {Location} from '@angular/common';
import {provideLocationStrategy} from '@angular/router/src/router_module';
import {BrowserPlatformLocation} from '@angular/platform-browser/src/browser/location/browser_platform_location';
describe('heroDetails', () => {
it('should call getHero after being created', () => {
const heroDetailsComponent = new HeroDetailsComponent(new ActivatedRoute(),
new MyHeroService(new MessageService([])),
new Location(provideLocationStrategy(new BrowserPlatformLocation(['anyParameter']), '/')));
spyOn(heroDetailsComponent, 'getHero');
heroDetailsComponent.ngOnInit();
expect(heroDetailsComponent.getHero()).toHaveBeenCalled();
});
});
我面临的困难是当我尝试创建一个新的 Location 时,它是 Hero-datail 组件的构造函数的必需参数。
第一个Location的参数是一个PlatformStrategy,所以我用provider来构建它。此外,提供者需要一个看起来很抽象的 PlatformLocation(),所以我选择了我能找到的唯一实现,即 BrowserPlatformLocation。
这里奇怪的是,IDE 确实找到了这些模块,因为我可以导航到它们。
此外,如果我注释掉该测试,该套件运行良好:
另外我也读过:
我怎样才能以正确的方式对其进行测试?我在哪里可以找到有关正确进行此类测试的更多信息?这个测试如何轻松模拟 Location 参数?
感谢您阅读本文
【问题讨论】:
标签: javascript angular unit-testing jasmine