【问题标题】:Testing @ContentChildren() in Angular 5在 Angular 5 中测试 @ContentChildren()
【发布时间】:2018-10-20 19:28:30
【问题描述】:

我需要测试我的@ContentChildren 是否使用 Jasmine 正确填充,但我无法让我的测试正常工作。碰巧有一个very similar question and answer here,但我的代码在下面指示的行上失败了。

代码如下:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, NO_ERRORS_SCHEMA } from '@angular/core';

import { RadioButtonGroupComponent } from './radio-button-group.component';

@Component({
  selector: 'sas-radio-button-test',
  template: `<sas-radio-button-group>
  <sas-radio-button text="Radio button 0" value="0" checked="true"></sas-radio-button>
  <sas-radio-button text="Radio button 1" value="1"></sas-radio-button>
  <sas-radio-button text="Radio button 2" value="2"></sas-radio-button>
</sas-radio-button-group>`,
})
class TestWrapperComponent {
}

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [TestWrapperComponent, RadioButtonGroupComponent, RadioButtonGroupComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestWrapperComponent);
    component = fixture.debugElement.children[0].componentInstance;
    fixture.detectChanges();
  });

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

  it('should have the correct number of children', () => {
    expect(component.radioButtons.length).toBe(3); // <!--- this is zero when it should be 3
  });
});

我的组件片段如下所示:

export class RadioButtonGroupComponent implements AfterContentInit {
    @ContentChildren(RadioButtonComponent) radioButtons: QueryList<RadioButtonComponent>;
    //...
}

谁能帮忙?

【问题讨论】:

  • 我试过这段代码,返回的长度等于3。你的RadioButtonGroupComponent里面一定有问题

标签: angular unit-testing typescript jasmine


【解决方案1】:

您可以将fixture.detectChanges(); 放在测试用例中(在it 内)并从beforeEach 中删除fixture.detectChanges()

it('should have the correct number of children', () => {
    fixture.detectChanges()
    expect(component.radioButtons.length).toBe(3); 
  });

beforeEach 是初始化步骤。更改应用于测试用例级别。

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 2016-11-23
    • 1970-01-01
    • 2020-09-12
    • 2018-08-23
    • 2017-10-11
    • 1970-01-01
    • 2018-07-25
    • 2018-09-23
    相关资源
    最近更新 更多