How to write testcase for @Input property. And check whether some value is present using ngIf directive within ng-container. So how to write test for such scenerio.
Here is my code. Please help me.
ChildComponent.ts
@Input() myInput;
ChildComponent.html
<ng-container *ngIf="myInput?.value1">
- Display some code
</ng-container>
<ng-container *ngIf="myInput?.value2">
- Display some code
</ng-container>
In this code, How can we check if these ngIfs actually works. I really need little clue here in writing test case. Since Angular is new to me.
Thanks a lot
CodePudding user response:
You can verify presence of html elements within your test fixture in your angular tests, in your test do something like this:
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be present if color is blue', () => {
component.color = 'blue';
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#elementThatIsPresentIfBlue')).not.toBeNull();
});
CodePudding user response:
The @input variable i:e myInput is set from the host component. In order to check the rendering of specific html
you can simulate the parent setting the input property.
In your test file, you can easily access the @Input variable using [componentInstance.myInput]
and after changing the input value, you can check the rendering of conditional html
element.
// In your test block
component.myInput = {value1: 'Val', value2: undefined};
// trigger manual data binding
fixture.detectChanges();
let firstEle = fixture.debugElement.nativeElement.querySelector(`selector`);
expect(firstEle).toBeTruthy();
component.myInput = {value1: undefined, value2: 'val'};
// trigger manual data binding
fixture.detectChanges();
let secondEle = fixture.debugElement.nativeElement.querySelector(`selector`);
expect(secondEle ).toBeTruthy();
References https://angular.io/guide/testing-components-scenarios#component-with-inputs-and-outputs
https://angular.io/guide/testing-components-basics#debugelement