Automate Login After Signup

Let's update the signup function so that newly added users are logged in automatically. Also, we’ll update the function tests accordingly.

We'll cover the following...

At the moment, we have two services that do what we need them to do (signup and login.) Now, we need signup to also call login so that newly created users are automatically logged into the application.

Our updated application code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>LetsGetLunch</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>
Login test case and login method

Update signup tests

Let’s first update our test for this new behavior of our signup method. Add the response we expect to receive from our test. Add the response for the login method just below signupResponse.

Press + to interact
// src/app/services/auth/auth.service.spec.ts
it('should return a user object with a valid username and password', () => {
const user = { 'username': 'myUser', 'password': 'password' };
const signupResponse = {
'__v': 0,
'username': 'myUser',
'password': '$2a$10$oF7YW1FyOSW3Gw7G4ThbO.ibduCgF3U0gVI/GE9fKQcGtVEBs0B.2',
'_id': '5a550ea739fbc4ca3ee0ce58',
'dietPreferences': []
};
const loginResponse = { 'token': 's3cr3tt0ken' }; // Add this
let response;
authService.signup(user).subscribe(res => {
response = res;
});
http.expectOne('{{EDUCATIVE_LIVE_VM_URL}}:3000/api/users').flush(signupResponse);
expect(response).toEqual(signupResponse);
http.verify();
});

Then, create what’s known as a spy within testing as follows:

  1. Import of at the top of our file which allows us to create an observable value.
Press + to interact
// src/app/services/auth/auth.service.spec.ts
import { of } from 'rxjs';
...
it('should return a user object with a valid username and password', () => {
const user = { 'username': 'myUser', 'password': 'password' };
const signupResponse = {
'__v': 0,
'username': 'myUser',
'password': '$2a$10$oF7YW1FyOSW3Gw7G4ThbO.ibduCgF3U0gVI/GE9fKQcGtVEBs0B.2',
'_id': '5a550ea739fbc4ca3ee0ce58',
'dietPreferences': []
};
const loginResponse = { 'token': 's3cr3tt0ken' };
let response;
authService.signup(user).subscribe(res => {
response = res;
});
spyOn(authService, 'login').and.callFake(() => of(loginResponse));
http.expectOne('{{EDUCATIVE_LIVE_VM_URL}}:3000/api/users').flush(signupResponse);
expect(response).toEqual(signupResponse);
http.verify();
});
  1. Add the spy below our call to authService.signup(). A spy tracks a function, allowing us to form expectations within our test about that function. It also lets us intercept calls to that function, manually providing its return values. In this case, we’re spying on the login method of our authService. ...