Created
March 10, 2019 08:41
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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