Skip to content

Instantly share code, notes, and snippets.

@Hakier
Created March 10, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hakier/c2f18d207e6ae368d30402e84d0c62e0 to your computer and use it in GitHub Desktop.
Save Hakier/c2f18d207e6ae368d30402e84d0c62e0 to your computer and use it in GitHub Desktop.
How to get an instance of structural directive to properly test if some value has been passed to it?
import { Component, Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
const showReflection: any = {};
@Directive({ selector: '[appShow]' })
export class UnlessDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
) { }
@Input() set appShow(show: boolean) {
showReflection.show = show;
if (show) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
@Component({
template: `
<h1>STRUCTURAL DIRECTIVE TEST</h1>
<h2 *appShow="displayExtraHeader">Lorem ipsum</h2>
`,
})
class StructuralDirectiveComponent {
displayExtraHeader = true;
}
fdescribe('Structural Directive', () => {
let component: StructuralDirectiveComponent;
let fixture: ComponentFixture<StructuralDirectiveComponent>;
let compiled: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
UnlessDirective,
StructuralDirectiveComponent,
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(StructuralDirectiveComponent);
compiled = fixture.debugElement.nativeElement;
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('HTML', () => {
beforeEach(() => {
component.displayExtraHeader = false;
fixture.detectChanges();
});
it('should render <h1>', () => {
expect(compiled.querySelector('h1')).not.toBeNull();
});
it('should pass displayExtraHeader to appShow', () => {
const directive1: any = fixture.debugElement.query(By.css('[appShow]'));
const directive2: any = fixture.debugElement.query(By.directive(UnlessDirective));
console.log(`>>> directive1`, directive1);
console.log(`>>> directive2`, directive2);
// directive1 and directive 2 are null
// @TODO: how to get an instance of structural directive?
expect(showReflection.show).toEqual(false);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment