1

I have some component TestComponent that, in it's template, uses a <mat-stepper>. Because of the context of the stepper, I have to programmatically advance to the next step rather than using the matStepperNext directive on a button. So my component looks like this:

test.component.ts

import { MatStepper } from '@angular/material/stepper'; //module loaded elsewhere, but is accesible

@Component({
  selector: 'app-test',
  template: '<mat-stepper #stepper>
               <mat-step>
                 <button (click)="completeStep()">Next</button>
               </mat-step>
               <mat-step></mat-step> <!-- etc. -->
             </mat-stepper>',
})
export class TestComponent {
  @ViewChild('stepper') stepper!: MatStepper;

  completeStep() {
    this.stepper.next();
  }
}

Now the trick is that I have to test that stepper.next() was called. Because I'm just using the <mat-dialog> directive, I never actually create an object of it in the class, nor is it a provider in the constructor, so I'm not really sure how to test it. I've tried a bunch of different things with no success, and my latest test is as follow:

test.component.spec.ts

describe('TestComponent', () => {
  let component: TestComponent,
  let fixture: ComponentFixture<TestCompnent>;

  beforeEach(async () => {
    await TestBed.ConfigureTestingModule({
      declarations: [TestComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  describe('completeStep', () => {
    it('should call stepper.next', () => {
      const stepperSpy = jasmine.createSpyObj('MatStepper', ['next']);
      component.stepper = stepperSpy;
      component.completeStep();
      expect(stepperSpy.next).toHaveBeenCalled();
    });
  });
});

But I just get the error

Expected spy MatStepper.next to have been called

PaulBunion
  • 346
  • 2
  • 18

1 Answers1

0

In before each add MatStepper to declarations array:

beforeEach(async () => {
  await TestBed.ConfigureTestingModule({
       declarations: [TestComponent, MatStepper],
  }).compileComponents();
});

And the test case should look like:

it('completeStep should call stepper.next', () => {     
   jest.spyOn(component.stepper, 'next');
   component.completeStep();
   expect(component.stepper.next).toHaveBeenCalled();
});
szelelaci
  • 163
  • 1
  • 12