在 Angular 单元测试中测试 URL 参数
Testing URL Params in Angular Unit Test
我正在尝试测试 URL 参数中包含的字符串。在我的打字稿文件中,我有方法:
checkURLParams() {
if (this.route.parent) {
this.route.parent.params.subscribe((params) => {
if (params['view'] === 'view') {
this.form.disable();
}
});
}
}
测试应该确保当参数包含字符串'view'时,该表单应该被禁用。
目前在我的规范文件中有:
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
RouterTestingModule,
ReactiveFormsModule
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
});
fit('test', fakeAsync(() => {
// Arrange
// Act
component.checkURLParams();
// Assert
expect(component.form.disabled).toBeTruthy();
}));
我看到了一些测试 URL 参数的不同方法的解决方案,但找不到在测试中模拟 URL 参数以包含 'view' 以禁用形式。解决此问题的最佳方法是什么?
我遇到过类似的情况,我需要测试 URL 和结果。
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
let location: Location;
let router: Router;
beforeEach(() => {
location = TestBed.inject(Location);
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
router = TestBed.inject(Router);
fixture.ngZone.run(() => {
router.initialNavigation();
});
});
it('test', waitForAsync(() => {
fixture.ngZone.run(async () => {
await router.navigate(['yourUrl/With/Params']);
fixture.detectChanges();
component.checkURLParams();
expect(component.form.disabled).toBeTruthy();
});
})
);
我正在尝试测试 URL 参数中包含的字符串。在我的打字稿文件中,我有方法:
checkURLParams() {
if (this.route.parent) {
this.route.parent.params.subscribe((params) => {
if (params['view'] === 'view') {
this.form.disable();
}
});
}
}
测试应该确保当参数包含字符串'view'时,该表单应该被禁用。
目前在我的规范文件中有:
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
RouterTestingModule,
ReactiveFormsModule
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
});
fit('test', fakeAsync(() => {
// Arrange
// Act
component.checkURLParams();
// Assert
expect(component.form.disabled).toBeTruthy();
}));
我看到了一些测试 URL 参数的不同方法的解决方案,但找不到在测试中模拟 URL 参数以包含 'view' 以禁用形式。解决此问题的最佳方法是什么?
我遇到过类似的情况,我需要测试 URL 和结果。
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
let location: Location;
let router: Router;
beforeEach(() => {
location = TestBed.inject(Location);
fixture = TestBed.createComponent(AppComponent);
component = fixture.debugElement.componentInstance;
router = TestBed.inject(Router);
fixture.ngZone.run(() => {
router.initialNavigation();
});
});
it('test', waitForAsync(() => {
fixture.ngZone.run(async () => {
await router.navigate(['yourUrl/With/Params']);
fixture.detectChanges();
component.checkURLParams();
expect(component.form.disabled).toBeTruthy();
});
})
);