简体   繁体   中英

how to write a unit test for angular child component with @input()

I have to write a test for a child component with @Input(). The output is an object and is used in view to populate the values after recieving from the parent. I have tried writing a test for this which doesn't seem to get pass. Any help would be appreciated, newbie to Angular and very very newbie to testing.

My test looks like this:

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');
  });
});

Component is:

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() { }

}

Understand these point properly:

  1. You should not cover unit tests for child component in your parent component.
  2. You should write unit test of component in their respective spec file only.
  3. You don't need to bother about external dependencies (in your case, it's child component), when writing unit tests for the component.
  4. You should provide the configuration either all the component dependencies, or you can include NO_ERROR_SCHEMA . So, this will not give error for including references of the all the used components in TestBed configuration. You can include NO_ERROR_SCHEMA as:

    schemas: [NO_ERROR_SCHEMA]

Hope, I cleared your doubts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM