Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find right button using text in angular 2 for unit test case

Tags:

angular

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>
&nbsp;&nbsp;
<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.

like image 983
Anil Avatar asked Jun 07 '18 21:06

Anil


People also ask

What the describe keyword is used for in Angular unit 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.

How do you write test cases for button clicks?

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.

What is the correct way to trigger a click event on button when testing an Angular component?

For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button.


1 Answers

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!

like image 171
Finn Mathis Avatar answered Sep 30 '22 16:09

Finn Mathis