avdeveloper
avdeveloper

Reputation: 549

How to do component test for mat stepper?

I have the below mat-stepper steps:

<button mat-raised-button (click)="isLinear = !isLinear" id="toggle-linear">
 {{!isLinear ? 'Enable linear mode' : 'Disable linear mode'}}
</button>
<mat-horizontal-stepper [linear]="isLinear" #stepper>
<mat-step [stepControl]="firstFormGroup">
<form [formGroup]="firstFormGroup">
  <ng-template matStepLabel>Fill out your name</ng-template>
  <mat-form-field>
    <mat-label>Name</mat-label>
    <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
  </mat-form-field>
  <div>
    <button mat-button matStepperNext>Next</button>
  </div>
 </form>
</mat-step>
<mat-step [stepControl]="secondFormGroup" label="Fill out your address">
<form [formGroup]="secondFormGroup">
  <mat-form-field>
    <mat-label>Address</mat-label>
    <input matInput formControlName="secondCtrl" placeholder="Ex. 1 Main St, New York, NY"
           required>
  </mat-form-field>
  <div>
    <button mat-button matStepperPrevious>Back</button>
    <button mat-button matStepperNext>Next</button>
  </div>
  </form>
 </mat-step>

How can I do a unit test to check if button next is clicked, it actually moves to the next index?

Upvotes: 1

Views: 1658

Answers (1)

Mehmet
Mehmet

Reputation: 21

See official documentation here

// Imports
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatStepperHarness, MatStepperNextHarness } from 
'@angular/material/stepper/testing';

// Declare your harness loader variable inside the describe block
describe('CreateLovedeedDialogComponent', () => {
    let loader: HarnessLoader;
});

// Reference the loader in beforeEach
beforeEach(() => {
    ...
    component = fixture.componentInstance;
    fixture.detectChanges();
    loader = TestbedHarnessEnvironment.loader(fixture);
});

it('should go forward when pressing the next button', async () => {
    const stepper = await loader.getHarness(MatStepperHarness);
    const steps = await stepper.getSteps();

    // Should have 6 steps
    expect(steps.length).toEqual(6);

    // The first step should be selected by default
    expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([true, false, false, false, false, false]);

    // Get and click on the first step's next button
    const firstStep = steps[0];
    let nextButton = await firstStep.getHarness(MatStepperNextHarness);
    await nextButton.click();

// The second step should be selected
    expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([false, true, false, false, false, false]);
});

In the above example, there is a stepper with 6 steps.

https://stackblitz.com/run?file=src/app/stepper-harness-example.ts

Upvotes: 2

Related Questions