【问题标题】:Testing Material components as a child component测试 Material 组件作为子组件
【发布时间】:2022-12-03 04:26:52
【问题描述】:

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

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

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

测试.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 已被调用

【问题讨论】:

    标签: angular typescript angular-material jasmine mat-stepper


    【解决方案1】:

    在每次将 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();
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 1970-01-01
      • 2018-08-01
      • 2018-10-12
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多