如何使用 @input() 为 Angular 子组件编写单元测试



我必须用@Input((为子组件编写一个测试。输出是一个对象,用于在从父级接收后在视图中填充值。我试过为此编写一个测试,但似乎没有通过。任何帮助将不胜感激,Angular 的新手和非常非常测试的新手。

我的测试如下所示:

import { async, ComponentFixture, TestBed, } from '@angular/core/testing';
import { MetricsComponent } from './scenario-flow.component';
describe('MetricsComponent', () => {
let component: MetricsComponent;
let fixture: ComponentFixture<MetricsComponent>;
const input = ['1', '2', '3','4', '5', '6', '7', '8', '9','10'];
const testinput = {id:'1', projectId:'1', name:'scenario One', 
attributes:null, structures:[], flows:[] };
beforeEach(async(() => {
TestBed.configureTestingModule({ 
declarations: [ MetricsComponent ]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MetricsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should show change in input', () => {
component.ParentMetrics = 'testinput';
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('div').innerText).toEqual('test 
input');
});
});

组件为:

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-metrics',
templateUrl: './metrics.component.html',
styleUrls: ['./metrics.component.scss']
})
export class MetricsComponent implements OnInit {
@Input() ParentMetrics:Metrics;
constructor() { }
ngOnInit() { }
}

正确理解这些要点:

  1. 不应在父组件中涵盖子组件的单元测试。
  2. 您应该仅在各自的规范文件中编写组件的单元测试。
  3. 在为组件编写单元测试时,您无需为外部依赖项(在您的情况下,它是子组件(而烦恼。
  4. 您应该提供所有组件依赖项的配置,也可以包含NO_ERROR_SCHEMA。因此,这不会在 TestBed 配置中包含所有已使用组件的引用时出错。 您可以将NO_ERROR_SCHEMA包括为:

    schemas: [NO_ERROR_SCHEMA]

希望,我消除了你的疑虑。

最新更新