Я пытаюсь расширить угловой тест JHipster и столкнулся с проблемой.
Моя цель состоит в том, чтобы имитировать неудачный вход в систему в компоненте Вход.Но я не могу получить ложную ошибку аутентификации от login.service.ts
.Я создал метод в mock-login.service.ts
, но тест не прошел.
Вывод на консоль: Uncaught (in promise): Object: {}
Вот мой тест: login.component.spec.ts Код на GitHub (без моего теста)
it('should fail authenticate upon login with wrong credentials', inject(
[],
fakeAsync(() => {
// GIVEN
const credentials = {
username: 'NonExistingUser',
password: 'WrongPassword',
rememberMe: true
};
comp.username = 'NonExistingUser';
comp.password = 'WrongPassword';
comp.rememberMe = true;
comp.credentials = credentials;
mockLoginService.returnAuthenticationError({}); // Here i try to imitate error
comp.credentials = credentials;
// WHEN
comp.login();
tick(); // simulate async
// THEN
expect(comp.authenticationError).toEqual(true);
expect(mockLoginService.loginSpy).toHaveBeenCalledWith(credentials);
expect(mockRouter.navigateSpy).not.toHaveBeenCalled();
})
));
login.component.ts GitHub
login() {
this.loginService
.login({
username: this.username,
password: this.password,
rememberMe: this.rememberMe
})
.then(() => {
this.authenticationError = false;
this.activeModal.dismiss('login success');
if (this.router.url === '/register' || /^\/activate\//.test(this.router.url) || /^\/reset\//.test(this.router.url)) {
this.router.navigate(['']);
}
this.eventManager.broadcast({
name: 'authenticationSuccess',
content: 'Sending Authentication Success'
});
// previousState was set in the authExpiredInterceptor before being redirected to login modal.
// since login is succesful, go to stored previousState and clear previousState
const redirect = this.stateStorageService.getUrl();
if (redirect) {
this.stateStorageService.storeUrl(null);
this.router.navigate([redirect]);
}
})
.catch(() => {
this.authenticationError = true;
});
}
mock-login.service.ts GitHub (без моего пользовательского метода)
export class MockLoginService extends SpyObject {
loginSpy: Spy;
logoutSpy: Spy;
registerSpy: Spy;
requestResetPasswordSpy: Spy;
cancelSpy: Spy;
constructor() {
super(LoginService);
this.setLoginSpy({});
this.returnAuthenticationError({});
this.logoutSpy = this.spy('logout').andReturn(this);
this.registerSpy = this.spy('register').andReturn(this);
this.requestResetPasswordSpy = this.spy('requestResetPassword').andReturn(this);
this.cancelSpy = this.spy('cancel').andReturn(this);
}
setLoginSpy(json: any) {
this.loginSpy = this.spy('login').andReturn(Promise.resolve(json));
}
setResponse(json: any): void {
this.setLoginSpy(json);
}
returnAuthenticationError(json:any): void {
this.loginSpy = this.spy('login').andReturn(Promise.reject(json));
}
}
login.service.ts GitHub
export class LoginService {
constructor(
private languageService: JhiLanguageService,
private principal: Principal,
private authServerProvider: AuthServerProvider
) {}
login(credentials, callback?) {
const cb = callback || function() {};
return new Promise((resolve, reject) => {
this.authServerProvider.login(credentials).subscribe(
data => {
this.principal.identity(true).then(account => {
// After the login the language will be changed to
// the language selected by the user during his registration
if (account !== null) {
this.languageService.changeLanguage(account.langKey);
}
resolve(data);
});
return cb();
},
err => {
this.logout();
reject(err);
return cb(err);
}
);
});
}
logout() {
this.authServerProvider.logout().subscribe();
this.principal.authenticate(null);
}
}
Я полагаю, что проблема заключается в моем маленьком знании и понимании насмешек и обещаний.