I am new to UI test cases. what I am trying to do is to validate text of button in my angular template.
Below are the button controls available in my angular template file
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Show/Hide</button>
<button type="button" class="btn btn-primary" (click)="filterModal.show()">Filter</button>
Below is my angular test
it('should have button with text show/hide',()=>{
const debug=fixture.debugElement;
const native=debug.nativeElement;
const buttonElem=native.querySelector('button:contains("show/hide")');
console.log(native);
expect(buttonElem.textContent).toContain('Show/Hide');
});
As I have two buttons in my template without any Id and with same class. I am trying to find right button with text value but it is failing with below error "SyntaxError: Failed to execute 'querySelector' on 'Element': 'button:contains("show/hide")' is not a valid selector."
What is the right way to test this scenario.
Edit: I am using Jasmine with karma for testing.
The describe code block represents the test suite for AppComponent. It contains specs and additional code that's used for testing AppComponent. beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite.
There are two prominent approaches when it comes to writing unit tests for button clicks in Angular: either you search the DOM for the button, perform an actual click and verify the expected behavior, or you simply call the component-code that will run when the button is clicked.
For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button.
Since neither fixture.debugElement.query(By.css('button[textContent="Show/Hide"]')
nor fixture.nativeElement.querySelector('button[textContent="Show/Hide"]')
works for me, I use a predicate function for that:
const buttonDebugElement = fixture.debugElement.query(
debugEl => debugEl.name === 'button' && debugEl.nativeElement.textContent === 'Show/Hide'
);
It is described in the Angular Docs here: https://angular.io/guide/testing-utility-apis#debugelement
Another way using the By.css helper and queryAll:
const buttonDebugElement = fixture.debugElement.queryAll(By.css('button').find(
buttonDebugEl => buttonDebugEl.nativeElement.textContent === 'Show/Hide'
);
Be aware that the text comparison is case sensitive!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With