【发布时间】:2020-03-31 21:03:51
【问题描述】:
我使用Spectator 编写我的Angular 8 测试并使用Jest 运行它们。我是前端单元测试的新手,所以我可能忽略了一些简单的事情;欢迎任何想法。
我有以下方法(在 Typescript 中),它根据当前 URL 是否与一组路径匹配(不包括 queryParams 和片段)返回布尔值:
// custom-breadcrumb.component.ts
private blacklistedPaths: string[] = [''];
constructor(private router: Router) {
}
hideBreadcrumb(): boolean {
let primaryUrlSegmentGroup: UrlSegmentGroup = this.router.parseUrl(this.router.url).root.children['primary'];
if(primaryUrlSegmentGroup == null){
return true;
}
let urlPath = primaryUrlSegmentGroup.segments.map((segment: UrlSegment) => segment.path).join('/');
return this.blacklistedPaths.some((path: string) => path === urlPath);
}
和
// custom-breadcrumb.component.html
<xng-breadcrumb [hidden]="hideBreadcrumb()">
<ng-container *xngBreadcrumbItem="let breadcrumb">
...
</ng-container>
</xng-breadcrumb>
我现在想用 Spectator 编写测试,它将根据几个可能的 url 验证布尔返回值。在 Java 中,我会用模拟对象模拟 Router 并执行以下操作:
when(mockObject.performMethod()).thenReturn(myReturnValue);
如何为Router 创建模拟?以及如何定义this.router.parseUrl(this.router.url).root.children['primary'] 的返回值?
这是我目前拥有的:
// custom-breadcrumb.component.spec.ts
import {SpectatorRouting, createRoutingFactory} from '@ngneat/spectator/jest';
describe('CustomBreadcrumbComponent', () => {
let spectator: SpectatorRouting<CustomBreadcrumbComponent>;
const createComponent = createRoutingFactory({
component: CustomBreadcrumbComponent,
declarations: [
MockComponent(BreadcrumbComponent),
MockPipe(CapitalizePipe)
],
routes: [{path: ''}] // I don't think this works
});
beforeEach(() => spectator = createComponent());
it('hideBreadcrumb - hide on homepage', () => {
// TODO set url path to ''
expect(spectator.component.hideBreadcrumb()).toBeTruthy();
});
it('hideBreadcrumb - show on a page other than homepage', () => {
//TODO set url path to 'test' for example
expect(spectator.component.hideBreadcrumb()).toBeFalsy();
});
});
我知道createRoutingFactory 提供了一个开箱即用的ActivatedRouteStub,但我无法用它做任何有意义的事情。
PS:我添加了 karma 作为标签,因为它可能有相同的解决方案,但如果我错了,请纠正我。
【问题讨论】:
标签: angular jestjs karma-jasmine ngmock angular-spectator