1

我有一些组件TestComponent,在它的模板中,使用<mat-stepper>. 由于步进器的上下文,我必须以编程方式前进到下一步,而不是matStepperNext在按钮上使用指令。所以我的组件看起来像这样:

测试组件.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();
  }
}

现在的诀窍是我必须测试那个stepper.next()被调用的东西。因为我只是使用<mat-dialog>指令,我从来没有在类中真正创建它的对象,也不是构造函数中的提供者,所以我不太确定如何测试它。我尝试了很多不同的方法都没有成功,我的最新测试如下:

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();
    });
  });
});

但我只是得到错误

预计间谍 MatStepper.next 已被调用

4

0 回答 0