问题
I am always getting this error randomly for differennt tests when I enable my login.spec.ts tests. Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'logout'
I tried to fake the logout method in authService using: spyOn(authService, 'logout').and.returnValues(true); But still it doesnt work. Please help figuring out the issue here.
login.component.ts
export class LoginComponent implements OnInit {
isLoggingIn = false;
constructor(
private authService: AuthService
) { }
ngOnInit() {
this.authService.logout();
}
}
authService.ts
@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']);
}
}
and now my
login.component.spec.ts
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();
});
});
回答1:
You have an error because you haven't configured the routes even you have used RouterTestingModule
here. Configure your imports
section of the spec as follows but I don't think calling logout
function at the onInit
is a proper implementation.
imports: [
RouterTestingModule.withRoutes([
{ path: 'logout', component: LogoutComponent }
]),
HttpClientTestingModule
]
Tell me if this works, and we'll figure out from there. I think even if this fix your problem It hardly test your test case.
来源:https://stackoverflow.com/questions/55336064/angular-unit-test-uncaught-error-uncaught-in-promise-error-cannot-match-an