typescript 将材料元件作为子元件进行测试

vcudknz3  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(121)

我有一个组件TestComponent,在它的模板中,使用了一个<mat-stepper>。由于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>指令,我从来没有在类中实际创建它的对象,也不是构造函数中的提供者,所以我真的不知道如何测试它。我已经尝试了很多不同的方法,但都没有成功,我最新的测试如下:

测试组件规范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

zpgglvta

zpgglvta1#

在每个声明数组之前添加MatStepper:

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

测试用例应如下所示:

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

相关问题