Good day developers . Im trying to test the show hide behaviour of a <li/>
tag according to a specific variable.
For that this <li/>
tag has an *ngIf
bound:
<ul js-selector="tab-list">
<li js-selector="tab"
*ngIf="isTabEnabled"
...
>
</li>
</ul>
then on my component tha variable this li tag is bound to would be like this:
@Component({
templateUrl: '',
})
export class Component implements OnInit{
public isTabEnabled: boolean;
constructor() {
this.isTabEnabled = false;
}
public ngOnInit(): void {
this.isTabEnabled = true/false =======> boolean value of a feature flag
}
}
thus in my test:
describe('The Component', () => {
let page: Page;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
...
],
declarations: [
Component,
ComponentStub,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;
page = new Page();
});
})
);
describe('When test ....',()=>{
it('Should show Tab if feature flag is enabled', () => {
const tab = page.getTab();
fixture.detectChanges();
component.isTabEnabled=true
expect(tab).toBeVisible();
});
it('Should not show Tab if feature flag is not enabled', () => {
const tab = page.getTab();
fixture.detectChanges();
component.isTabEnabled=false
expect(tab).not.toBeVisible();
});
}
class Page {
private _el: HTMLElement;
constructor() {
this._el = fixture.nativeElement;
}
getTab(): HTMLElement {
return this._el.querySelector('[js-selector="tab"]');
} }
});
But i keep receiving this error
Received element is not visible:
<li js-selector="tab" />
Could you help me on this simple test...find the problem of its fail. Thanks in advance!!!
CodePudding user response:
I think you're missing a fixture.detectChanges
after changing isTabEnabled
and getting the reference to the HTML element too early.
Try this:
it('Should show Tab if feature flag is enabled', () => {
// !! first fixture.detectChanges() calls ngOnInit
fixture.detectChanges();
component.isTabEnabled=true;
// !! call fixture.detectChanges() again so the view updates with the
// new value of isTabEnabled
fixture.detectChanges();
!! get the value of the HTML element now
const tab = page.getTab();
expect(tab).toBeVisible();
});
// !! same thing here
it('Should not show Tab if feature flag is not enabled', () => {
fixture.detectChanges();
component.isTabEnabled=false
fixture.detectChanges();
const tab = page.getTab();
expect(tab).not.toBeVisible();
});