将组件模板包含在Angular的单元测试中

问题描述 投票:11回答:1

使用Angular 4,可以测试组件的模板,例如,检查单击按钮是否触发了预期的方法和类似的东西。

但是如何将模板包括在测试范围内?默认情况下,它们不是(与Karma + Jasmine + Istanbul一起使用Angular CLI测试)。

angular jasmine karma-runner code-coverage istanbul
1个回答
0
投票

我认为,您只能测试单击时调用的函数,因为您无需验证是否单击角就会调用此函数。

但是,如果您想以任何方式对其进行测试,可以这样做

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers: [  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  }));
});

it('should click on button', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click(); 
// here you can test you code or just check that your function have been called like in the example bellow 

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  });
}));
© www.soinside.com 2019 - 2024. All rights reserved.