首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将材料部件作为子组件进行测试

将材料部件作为子组件进行测试
EN

Stack Overflow用户
提问于 2021-12-10 22:59:06
回答 1查看 128关注 0票数 1

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

test.component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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被称为

EN

回答 1

Stack Overflow用户

发布于 2022-12-02 20:18:48

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

代码语言:javascript
复制
beforeEach(async () => {
  await TestBed.ConfigureTestingModule({
       declarations: [TestComponent, MatStepper],
  }).compileComponents();
});

测试用例应该如下所示:

代码语言:javascript
复制
it('completeStep should call stepper.next', () => {     
   jest.spyOn(component.stepper, 'next');
   component.completeStep();
   expect(component.stepper.next).toHaveBeenCalled();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70311236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档