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

标签 angular testing

我必须使用 @Input() 为子组件编写测试。输出是一个对象,在从父级接收后在 View 中使用它来填充值。我尝试为此编写一个测试,但似乎没有通过。任何帮助将不胜感激,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 包含为:

    架构:[NO_ERROR_SCHEMA]

希望我消除了你的疑虑。

关于angular - 如何使用 @input() 为 Angular 子组件编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57387388/

相关文章:

android - Espresso 中多个 View 的断言

angular - npm install 没有一个好的错误就被杀死了

angular - 尽管发现错误,rxjs 仍发生取消订阅

angular - 类型 'clientX' 上不存在属性 'Event'。 Angular2 指令

javascript - 无法使用 ng-packagr 获取已发布的包

javascript - 在 ExtJs 中模拟点击 tabpanel

android - 仪器测试运行器 : What does android:functionalTest achieve?

javascript - 我怎样才能在 Jasmine 中拥有 beforeAll 功能? (不是 coffeeScript)

c# - 如何对可空类型使用 Mock 设置

javascript - 为 angular2 创建管道以将 JSON 迭代到数组