Bird
Raised Fist0
Angularframework~20 mins

Testing forms and user interactions in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Angular Forms Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a user submits a form with invalid inputs?

Consider an Angular standalone component with a reactive form that requires a non-empty email input. What will be the form's valid status and error state after submitting the form with an empty email field?

Angular
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-email-form',
  standalone: true,
  template: `
    <form [formGroup]="emailForm" (ngSubmit)="onSubmit()">
      <input formControlName="email" placeholder="Email" aria-label="Email input" />
      <button type="submit">Submit</button>
      <div *ngIf="emailForm.controls.email.invalid && emailForm.controls.email.touched">
        Email is required.
      </div>
    </form>
  `
})
export class EmailFormComponent {
  emailForm = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email])
  });

  onSubmit() {
    this.emailForm.markAllAsTouched();
    console.log('Form valid:', this.emailForm.valid);
    console.log('Email errors:', this.emailForm.controls.email.errors);
  }
}
AThe form is invalid, but the email control has no errors because it was not touched.
BThe form is invalid, and the email control has an error object indicating 'required' and 'email' validation failures.
CThe form is valid because the submit button was clicked, and the email control has no errors.
DThe form is valid, but the email control has an error object indicating 'required' validation failure.
Attempts:
2 left
💡 Hint

Think about what Angular does when a required field is empty and the form is submitted.

state_output
intermediate
2:00remaining
What is the value of the form control after user input?

Given a template-driven Angular form with an input bound to ngModel, what will be the value of the username property after the user types 'Alice' into the input?

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-user-form',
  standalone: true,
  template: `
    <form>
      <input name="username" [(ngModel)]="username" aria-label="Username input" />
    </form>
    <p>Username: {{ username }}</p>
  `
})
export class UserFormComponent {
  username = '';
}
AThe username property will be null because the input is not inside a form tag.
BThe username property remains an empty string because ngModel does not update automatically.
CThe username property will be undefined because the input lacks a form control.
DThe username property will be 'Alice' after the user types it.
Attempts:
2 left
💡 Hint

Remember how two-way binding with [(ngModel)] works in Angular.

📝 Syntax
advanced
2:00remaining
Which option correctly disables a submit button when the form is invalid?

In an Angular reactive form, you want to disable the submit button if the form is invalid. Which template snippet correctly implements this behavior?

Angular
<form [formGroup]="myForm" (ngSubmit)="submit()">
  <button type="submit" [disabled]="???">Submit</button>
</form>
A[disabled]="myForm.invalid"
B[disabled]="!myForm.valid"
C[disabled]="myForm.status === 'INVALID'"
D[disabled]="myForm.controls.submit.disabled"
Attempts:
2 left
💡 Hint

Check the form group's properties that indicate validity.

🔧 Debug
advanced
2:00remaining
Why does the form not update the model on input change?

In this Angular template-driven form, the input value changes but the component property does not update. What is the cause?

Angular
<form>
  <input name="email" [(ngModel)]="email" aria-label="Email input" />
</form>

export class EmailComponent {
  email = '';
}
AThe FormsModule is not imported in the module, so ngModel does not work.
BThe input is missing a type attribute, so Angular ignores the binding.
CThe email property is not initialized, so it cannot update.
DThe input lacks a formControlName directive, so it cannot bind.
Attempts:
2 left
💡 Hint

Check module imports related to forms.

🧠 Conceptual
expert
3:00remaining
How does Angular's signal-based form state improve user interaction testing?

Angular 17 introduced signals for reactive forms. How does using signals for form state improve testing user interactions compared to traditional observables?

ASignals replace the need for form controls, so forms become static and easier to test.
BSignals automatically mock user events, so no manual event simulation is needed in tests.
CSignals provide synchronous, immediate access to form state, making tests simpler and more predictable without needing async handling.
DSignals delay form state updates until after tests complete, preventing race conditions.
Attempts:
2 left
💡 Hint

Think about how signals differ from observables in timing and access.

Practice

(1/5)
1. What is the primary purpose of testing forms in Angular applications?
easy
A. To improve the app's visual design
B. To ensure the app correctly handles user input and form validation
C. To speed up the app's loading time
D. To reduce the size of the app bundle

Solution

  1. Step 1: Understand form testing goals

    Testing forms focuses on verifying that user inputs are handled correctly and validations work as expected.
  2. Step 2: Differentiate from unrelated goals

    Visual design, loading speed, and bundle size are unrelated to form testing.
  3. Final Answer:

    To ensure the app correctly handles user input and form validation -> Option B
  4. Quick Check:

    Form testing = user input handling [OK]
Hint: Form tests check input handling and validation only [OK]
Common Mistakes:
  • Confusing form testing with UI styling
  • Thinking form tests improve app speed
  • Assuming form tests reduce bundle size
2. Which Angular testing utility is commonly used to create a test environment for components with forms?
easy
A. TestBed
B. HttpClientTestingModule
C. RouterTestingModule
D. NgModule

Solution

  1. Step 1: Identify Angular testing utilities

    TestBed is the main utility to configure and create a test environment for components, including those with forms.
  2. Step 2: Exclude unrelated modules

    HttpClientTestingModule is for HTTP tests, RouterTestingModule for routing, and NgModule is a decorator, not a testing utility.
  3. Final Answer:

    TestBed -> Option A
  4. Quick Check:

    TestBed sets up component tests [OK]
Hint: Use TestBed to set up component tests with forms [OK]
Common Mistakes:
  • Confusing TestBed with HTTP or routing modules
  • Using NgModule instead of TestBed for testing
  • Not importing TestBed in test files
3. Given this test snippet, what will be the value of component.form.value.name after simulating user input?
component.form.controls['name'].setValue('Alice');
fixture.detectChanges();
medium
A. undefined
B. '' (empty string)
C. null
D. 'Alice'

Solution

  1. Step 1: Understand setValue effect on form control

    Calling setValue('Alice') sets the 'name' control's value to 'Alice'.
  2. Step 2: Confirm form value after change detection

    After fixture.detectChanges(), the form reflects the updated value.
  3. Final Answer:

    'Alice' -> Option D
  4. Quick Check:

    setValue updates form control value [OK]
Hint: setValue changes form control value immediately [OK]
Common Mistakes:
  • Assuming value stays undefined without submit
  • Confusing setValue with patchValue
  • Forgetting to call detectChanges
4. In this test code, what is the main issue causing the test to fail?
it('should update form on input', () => {
  const input = fixture.nativeElement.querySelector('input[name="email"]');
  input.value = 'test@example.com';
  // Missing event dispatch here
  fixture.detectChanges();
  expect(component.form.value.email).toBe('test@example.com');
});
medium
A. fixture.detectChanges() is called too early
B. The selector for input is incorrect
C. The input event is not dispatched after changing input value
D. The form control name is misspelled

Solution

  1. Step 1: Identify missing user interaction simulation

    After setting input.value, the input event must be dispatched to update Angular form bindings.
  2. Step 2: Understand effect of missing event

    Without dispatching the event, Angular does not detect the change, so form value remains unchanged.
  3. Final Answer:

    The input event is not dispatched after changing input value -> Option C
  4. Quick Check:

    Dispatch input event to update form [OK]
Hint: Always dispatch input/change events after setting input values [OK]
Common Mistakes:
  • Forgetting to dispatch input or change events
  • Assuming detectChanges alone updates form
  • Using wrong input selectors
5. You want to test a form submission that disables the submit button while processing and re-enables it after success. Which approach correctly tests this user interaction?
hard
A. Simulate form input, trigger submit event, check button disabled state before and after async operation
B. Only check if the submit button is disabled on component load
C. Call the submit method directly without simulating user input or events
D. Test the button's CSS class changes without triggering form submission

Solution

  1. Step 1: Simulate realistic user actions

    Testing should simulate user input and submit event to trigger form submission logic.
  2. Step 2: Verify button state changes during async process

    Check that the submit button disables during processing and re-enables after success to confirm correct interaction.
  3. Final Answer:

    Simulate form input, trigger submit event, check button disabled state before and after async operation -> Option A
  4. Quick Check:

    Test full user flow including async button state [OK]
Hint: Test full submit flow including button state changes [OK]
Common Mistakes:
  • Testing button state only on load
  • Skipping user input simulation
  • Ignoring async operation effects