How would I approach writing a unit test for this function? When the form is submitted, it sends a POST request to get a login token. With the token response it then sends another request to get the specific user details.
Here is the function:
// Log the user in and save the token, then get the details
onLoginSubmit() {
this.loggingIn = true;
// request the token then the details for the user based off the token
this.userService
.LoginUser(this.loginForm.value.username, this.loginForm.value.password)
.pipe(
tap(res => {
// console.log('Obtained Token:', res);
localStorage.setItem('login_token', res.token);
// this.utilityService.SetLocalStorage('login_token', res.token, 1, 'd');
}),
concatMap(() => this.userService.GetTokenDetails()),
)
.subscribe(
res => {
// console.log('Obtained User Data:', res);
localStorage.setItem('user', res.user);
// this.utilityService.SetLocalStorage('user', res.user, 1, 'd');
this.NavigateToRoute();
},
() => {
this.loggingIn = false;
},
);
}
Here are the service functions:
// logs in the user
LoginUser(email, password): Observable<any> {
return this.utilityservice.post('universal/login', { email, password }, this.utilityservice.GetHeaders());
}
// gets details of the current logged in user
GetTokenDetails() {
return this.utilityservice.get('universal/userAPI', { whoami: '' });
}
For unit tests I am assuming I need to create a mock service where these functions will return a valid response like the following:
// logs in the user
LoginUser(email, password): Observable<any> {
return { res: { token: 'test' } };
}
Is this the right approach or am I completely wrong? Also when it comes to E2E testing for my login page, I am essentially simulating a user in each test by writing code that simulates clicking form buttons and inputting values then checking to make sure I get valid responses or am I over complicating it?