【问题标题】:Angular 2 test ng-contentAngular 2 测试 ng-content
【发布时间】:2017-05-14 15:27:04
【问题描述】:

我想知道是否有一种方法可以在不创建宿主元素的情况下测试 ng-content

例如,如果我有警报组件 -

@Component({
  selector: 'app-alert',
  template: `
    <div>
      <ng-content></ng-content>
    </div>
  `,
})

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

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

  it('should display the ng content', () => {

  });

如何在不创建宿主元素包装器的情况下设置ng-content

【问题讨论】:

标签: javascript angular


【解决方案1】:

您必须创建另一个包含此测试组件的虚拟测试组件,即。 app-alert

@Component({
  template: `<app-alert>Hello World</app-alert>`,
})
class TestHostComponent {}

使 TestHostComponent 成为测试台模块的一部分

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

然后实例化这个测试组件,检查它是否包含 ng-content 部分,即。 “你好世界”文本

it('should show ng content content', () => {
    const testFixture = TestBed.createComponent(TestHostComponent);

    const de: DebugElement = testFixture.debugElement.query(
      By.css('div')
    );
    const el: Element = de.nativeElement;

    expect(el.textContent).toEqual('Hello World');
});

【讨论】:

  • 我最终使用了 Spectator。
【解决方案2】:

我想知道和你一样的事情:

看完后:Angular projection testing

我最终得到了这样的结果:

@Component({
template: '<app-alert><span>testing</span></app-alert>'
})
export class ContentProjectionTesterComponent {
}

describe('Content projection', () => {

let component: ContentProjectionTesterComponent;
let fixture: ComponentFixture<ContentProjectionTesterComponent>;

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

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

it('Content projection works', async () => {
let text = 'testing';
fixture = TestBed.createComponent(ContentProjectionTesterComponent);
component = fixture.componentInstance;
let innerHtml = fixture.debugElement.query(By.css('span')).nativeElement.innerHTML;
expect(innerHtml).toContain(text);
});
});

【讨论】:

  • 并不是这个问题的真正答案,因为它被专门要求在不创建虚拟主机的情况下进行测试......这里所做的正是他试图避免的
  • 优秀的解决方案,比这容易得多:stackoverflow.com/a/45998053/1845013
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多