我有一个检查当前URL是什么的方法,如果URL是'/',那么它将导航到特定页面(/ test)。代码本身正在工作,但是我在测试中设置URL时遇到了麻烦,因此无法通过“ /”检查。当我控制台注销url时,在测试中得到了“ function(){...}”,但是在浏览器中却得到了URL字符串。
public determineLandingPage(): void {
console.log(this.router.url)
if (this.router.url == "/") {
this.router.navigate(["/test"]);
}
}
测试文件::
import { LandingPage } from './generate-landing-page';
import { RouterTestingModule } from '@angular/router/testing';
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import * as TypeMoq from 'typemoq';
import { SpyLocation } from '@angular/common/testing';
import { Location, CommonModule } from '@angular/common';
import { Component } from '@angular/core';
@Component({
template: ''
})
class TestComponent {}
describe('LandingPage Tests', () => {
let routerMock : TypeMoq.IMock<Router>;
let service : LandingPage;
beforeEach( () => {
routerMock = TypeMoq.Mock.ofType<Router>();
TestBed.configureTestingModule({
imports: [
CommonModule,
RouterTestingModule.withRoutes([
{ path: '', component: TestComponent},
]),
],
declarations: [ TestComponent ],
providers: [{
provide: Router,
useFactory: () => {
return routerMock.object;
}
}
]
}).compileComponents();
service = new LandingPage(routerMock.object);
});
describe('determineLandingPage Tests', () => {
it('should navigate to test', async() => {
routerMock.setup(x => x.navigateByUrl('/'));
service.determineLandingPage();
routerMock.verify(x => x.navigate(TypeMoq.It.isValue(['/test'])), TypeMoq.Times.atLeastOnce());
});
});
});