当我启用login.spec.ts测试时,我总是随机地为不同的测试获取此错误。未捕获错误:未捕获(在承诺中):错误:无法匹配任何路由。网址细分:'退出'
我尝试使用以下命令伪造authService中的logout方法:spyOn(authService,'logout')。and.returnValues(true);但它仍然没有用。请帮助解决这个问题。
export class LoginComponent implements OnInit {
isLoggingIn = false;
constructor(
private authService: AuthService
) { }
ngOnInit() {
this.authService.logout();
}
}
@Injectable()
export class AuthService {
public userSource: BehaviorSubject<string | undefined> = new BehaviorSubject<string | undefined>(undefined);
constructor(
private myRoute: Router) {
}
logout() { // TODO: Right now this is fake logout. We need to either destroy express session or cookie.
this.userSource.next(undefined);
this.myRoute.navigate(['logout']);
}
}
而现在我的
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
providers: [ AuthService,
ConfigService
],
imports: [ RouterTestingModule,
HttpClientTestingModule ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
你有一个错误,因为你没有配置路线,即使你在这里使用过RouterTestingModule
。配置你的规范的imports
部分如下,但我不认为在logout
调用onInit
函数是一个正确的实现。
imports: [
RouterTestingModule.withRoutes([
{ path: 'logout', component: LogoutComponent }
]),
HttpClientTestingModule
]
告诉我这是否有效,我们会从那里弄清楚。我认为即使这可以解决您的问题,也很难测试您的测试用例。