Search⌘ K
AI Features

Tests for Signup Form

Explore how to write effective tests for the Angular signup form. Understand interacting with DOM elements using fixture.debugElement and By.css selectors, managing asynchronous test zones with async, and resolving scoping issues to ensure stable and accurate component testing.

Because we’re testing our component’s functionality, we’ll need to interact with the DOM elements, as we did earlier when we were manually creating users in our browser. To do this, we’ll create a class for our view to give us an easier way to interact with our component.

This is our updated 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>
SignupComponent failing test fixed

Add SignupPage class

Just above MockAuthService, add the following class:

  1. Declare a few variables which correspond to the various elements in the template through the method addPageElements.
  2. Access these using fixture.debugElement.query() to query the various elements within the template using By.css().
  3. Within By.css(), pass in standard CSS selectors to get handles on the various elements within the page for the “submit” button and form inputs.
TypeScript 3.3.4
// src/app/signup/signup.component.spec.ts
class SignupPage {
submitBtn: DebugElement;
usernameInput: HTMLInputElement;
passwordInput: HTMLInputElement;
dietPreference: DebugElement[];
addPageElements() {
this.submitBtn = fixture.debugElement.query(By.css('button'));
this.usernameInput = fixture
.debugElement
.query(By.css('[name=username]'))
.nativeElement;
this.passwordInput = fixture
.debugElement
.query(By.css('[name=password]'))
.nativeElement;
this.dietPreference = fixture
.debugElement
.queryAll(By.css('[name=preference]'));
}
}
class MockAuthService {
signup(credentials) { }
}
describe('SignupComponent', () => {
...
});
...