gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:16:25 25 4
gpt4 key购买 nike

我必须使用@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com