如何在单元测试用例中使用角度2中的文本查找右键

Ani*_*nil 5 angular

我是UI测试用例的新手。我想做的是验证我的角度模板中的按钮文本。

以下是我的角度模板文件中可用的按钮控件

<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>
Run Code Online (Sandbox Code Playgroud)

以下是我的角度测试

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');
  });
Run Code Online (Sandbox Code Playgroud)

因为我的模板中有两个没有任何ID且具有相同类的按钮。我正在尝试找到带有文本值的右键,但是它失败,并显示以下错误“ SyntaxError:无法在'Element'上执行'querySelector':'button:contains(“ show / hide”)'不是有效的选择器。”

什么是测试此方案的正确方法。

编辑:我使用茉莉与业力进行测试。

小智 5

由于既不适合我fixture.debugElement.query(By.css('button[textContent="Show/Hide"]')也不fixture.nativeElement.querySelector('button[textContent="Show/Hide"]')适合我,我为此使用了谓词函数:

const buttonDebugElement = fixture.debugElement.query(
  debugEl => debugEl.name === 'button' && debugEl.nativeElement.textContent === 'Show/Hide'
);
Run Code Online (Sandbox Code Playgroud)

它在此处的 Angular 文档中进行了描述:https : //angular.io/guide/testing-utility-apis#debugelement

另一种使用 By.css helper 和 queryAll 的方法:

const buttonDebugElement = fixture.debugElement.queryAll(By.css('button').find(
  buttonDebugEl => buttonDebugEl.nativeElement.textContent === 'Show/Hide'
);
Run Code Online (Sandbox Code Playgroud)

请注意,文本比较区分大小写!


Ani*_*nil 1

为我自己的问题提供答案。我尝试了下面的解决方案,它对我有用。不确定这是否是最好的方法。

首先我更新了我的 HTML 代码。将“按钮”元素转换为“输入”类型元素。

<input type="button" class="btn btn-primary" (click)="staticModal.show()" value="Show/Hide"/>
&nbsp;&nbsp;
<button type="button" class="btn btn-primary" (click)="filterModal.show()">Filter</button>
Run Code Online (Sandbox Code Playgroud)

其次,我修改了我的测试用例,如下所示。

it('should have button with text show/hide',()=>{
    const debug=fixture.debugElement.query(By.css('input[value="Show/Hide"]'));
    const native=debug.nativeElement;
    const buttonElem=native;    
    expect(buttonElem.value).toContain('Show/Hide');
  });
Run Code Online (Sandbox Code Playgroud)

这对我有用。