Extending JHipster tests - promise problem
I am trying to extend JHipster's Angular spec test and encountered a problem.
My goal is to imitate fail login in Login component. But I am not able to receive a fake authentication error from login.service.ts
. I've created a method in mock-login.service.ts
but the test fails to pass.
Console output: Uncaught (in promise): Object: {}
Here is my test: login.component.spec.ts Code on GitHub (without my test)
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 (without my custom method)
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);
}
}
I guess that problem is situated in my little knowlegde and understanding mocks and promises.
javascript typescript unit-testing promise jhipster
add a comment |
I am trying to extend JHipster's Angular spec test and encountered a problem.
My goal is to imitate fail login in Login component. But I am not able to receive a fake authentication error from login.service.ts
. I've created a method in mock-login.service.ts
but the test fails to pass.
Console output: Uncaught (in promise): Object: {}
Here is my test: login.component.spec.ts Code on GitHub (without my test)
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 (without my custom method)
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);
}
}
I guess that problem is situated in my little knowlegde and understanding mocks and promises.
javascript typescript unit-testing promise jhipster
add a comment |
I am trying to extend JHipster's Angular spec test and encountered a problem.
My goal is to imitate fail login in Login component. But I am not able to receive a fake authentication error from login.service.ts
. I've created a method in mock-login.service.ts
but the test fails to pass.
Console output: Uncaught (in promise): Object: {}
Here is my test: login.component.spec.ts Code on GitHub (without my test)
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 (without my custom method)
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);
}
}
I guess that problem is situated in my little knowlegde and understanding mocks and promises.
javascript typescript unit-testing promise jhipster
I am trying to extend JHipster's Angular spec test and encountered a problem.
My goal is to imitate fail login in Login component. But I am not able to receive a fake authentication error from login.service.ts
. I've created a method in mock-login.service.ts
but the test fails to pass.
Console output: Uncaught (in promise): Object: {}
Here is my test: login.component.spec.ts Code on GitHub (without my test)
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 (without my custom method)
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);
}
}
I guess that problem is situated in my little knowlegde and understanding mocks and promises.
javascript typescript unit-testing promise jhipster
javascript typescript unit-testing promise jhipster
asked Nov 20 at 8:38
rupertoss
113
113
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389076%2fextending-jhipster-tests-promise-problem%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389076%2fextending-jhipster-tests-promise-problem%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown