Testing dynamic components

Last updated 6 months ago
dynamic.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-dynamic",
template: `
<p class="dynamic">
dynamic works!
</p>
`,
styles: []
})
export class DynamicComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
consume-dynamic.component.ts
import {
Component,
ComponentFactoryResolver,
OnInit,
ViewContainerRef
} from "@angular/core";
import { DynamicComponent } from "../dynamic/dynamic.component";
@Component({
selector: "app-consume-dynamic",
template: `
<p>
consume-dynamic works!
</p>
`,
styles: []
})
export class ConsumeDynamicComponent implements OnInit {
constructor(
private resolver: ComponentFactoryResolver,
private ref: ViewContainerRef
) {}
ngOnInit() {
const factory = this.resolver.resolveComponentFactory(DynamicComponent);
this.ref.createComponent(factory);
}
}
consume-dynamic.component.spec.ts
describe("ConsumeDynamicComponent", () => {
let host: SpectatorWithHost<ConsumeDynamicComponent>;
const createHost = createHostComponentFactory({
declarations: [DynamicComponent],
entryComponents: [DynamicComponent],
component: ConsumeDynamicComponent
});
it("should work", () => {
host = createHost(`<app-consume-dynamic></app-consume-dynamic>`);
expect(host.component).toBeDefined();
});
it("should render the dynamic component", () => {
host = createHost(`<app-consume-dynamic></app-consume-dynamic>`);
expect(host.queryHost(".dynamic")).toHaveText("dynamic works!");
});
});