gpt4 book ai didi

angular - 如何在 Angular 2 中测试解析路径?

转载 作者:行者123 更新时间:2023-12-04 17:56:23 25 4
gpt4 key购买 nike

我正在尝试测试一个订阅路由器事件的简单组件,但我不知道如何模拟该部分代码。错误如下:无法读取未定义的“成对”属性。

Cannot read property 'pairwise' of undefined

这是我的测试:

describe('AppComponent', function () {
let fixture: ComponentFixture<AppComponent>;
var tendersServiceStub = {};
var scrollServiceStub = {};
var routerStub = {};

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [
{provide: TendersService, useValue: tendersServiceStub},
{provide: ScrollService, useValue: scrollServiceStub},
{provide: Router, useValue: routerStub}
],
imports: [RouterTestingModule],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges()
});
}));

it('should instantiate component', () => {
// console.log(fixture); UNDEFINED
});
});

这是组件:

export class AppComponent {
appTitle: string = 'Magic';

constructor(private router: Router, private tendersService: TendersService, private scrollService: ScrollService) {
this.router.events.pairwise().subscribe((e) => {
if ((e[0] instanceof NavigationEnd) && (e[1] instanceof NavigationStart)) {
this.resetSearchCache(e);
}
})
}

private resetSearchCache(e: any) {
if ((e[1].url == '/home') || (e[1].url == '/advancedSearch')) {
if (!e[0].url.includes('/detail')) {
//DO SOMETHING
}
}
}

}

有什么想法吗?

提前致谢。

最佳答案

您可以只添加 events 属性并将该值设为发出事件数组的 Observable

import 'rxjs/add/observable/of';

let mockRouter = {
// see notes below. this may be incorrect
events: Observable.of([ new NavigationStart(1, '/'),
new NavigationEnd(1, '/', '/home')])
};

另请参阅 NavigationEnd 的文档, NavigationStart , 和 RoutesRecognized .根据我的测试,该数组实际上由开始事件上的 [NavigationStart, RoutesRecognized] 和结束事件上的 [RoutesRecognized, NavigationEnd] 组成。所以你的逻辑可能不正确。

另一种选择是只使用真正的路由。有时这可能是有益的,而且设置起来并不难。例如,在您的情况下,您可以只将一个虚拟组件添加到 home 路由转到的测试中。然后使用 RouterTestingModule.withRoutes

配置路由
@Component({
template: `
`
})
class HomeComponent {}

describe('WelcomeComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
let router: Router;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule.withRoutes([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }
])],
declarations: [ AppComponent, HomeComponent ],
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
router = TestBed.get(Router);
router.initialNavigation();
});
});

有了这个,第一个路由事件将被触发。此外,如果您愿意,还可以通过导航到其他地方,使用 Router 手动触发其他事件。

关于angular - 如何在 Angular 2 中测试解析路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com