【问题标题】:How to access @Input property in angular unit test如何在角度单元测试中访问@Input 属性
【发布时间】:2020-10-14 10:14:34
【问题描述】:

我正在为一个具有 @Input 属性的简单角度组件编写一个有趣的单元测试。

这是我的组件

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-title',
  template: '<h2 id="title" class="title">{{title}}</h2>',
  styleUrls: ['./title.component.scss'],
})
export class TitleComponent implements OnInit {

  @Input() title;
  constructor() { }

  ngOnInit() {
  }

}

我的单元测试文件

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
      ],
      declarations: [TitleComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TitleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should show TEST INPUT', () => {
    component.title = 'test title';
    fixture.detectChanges();
    const input = fixture.nativeElement.querySelector('h2').innerText;

    console.log(input);
    expect(input).toEqual('test title');
  });
});

console.log(input) 始终未定义,我的测试用例失败。 我在这里做错了什么??????

【问题讨论】:

    标签: angular jestjs angular-unit-test


    【解决方案1】:

    应该是innerHTMLtextContent 而不是innerText。然后就可以了。

    fixture.nativeElement.querySelector('h2').innerHTML;
    

    原因是 jest 使用了 JSDom,而 JSDom 中的 innerText 属性还没有实现。 innerText implementation #1245

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多