【问题标题】:How to use predicate in angular2如何在angular2中使用谓词
【发布时间】:2017-01-10 07:45:53
【问题描述】:

我使用angular2 创建了一个登录页面。它有两个输入字段userNamepassword。该登录名中有一个按钮。 当我要为loginComponent 编写测试用例时,必须使用predicate 来识别button。这是我的测试用例。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { LoginComponent } from './login.component';


export class LoginComponentTest {
  constructor(public loginComponent: LoginComponent){
    this.loginComponent.logIn('Chathura', '1234');

  }
}

describe('LoginComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        LoginComponent
      ],
    })
  });

  const fixture = TestBed.createComponent(LoginComponent);

  const button = fixture.query(predicate: Predicate<DebugElement>, scope?: Function) : DebugElement

});

我将通过提供输入值进行测试,然后单击登录按钮并查看接下来会发生什么。

我无法找到正确使用谓词的正确教程。

【问题讨论】:

    标签: angular testing typescript karma-jasmine


    【解决方案1】:

    创建Predicate 的最简单方法是使用By 静态方法之一,即cssdirective

    const button = fixture.debugElement.query(By.css('.the-button')).nativeElement;
    

    By.css 让您传递任何 css 选择器。 query 的结果将是 DebugElement,因此如果要与原生 DOM 元素交互,则需要获取 nativeElement

    【讨论】:

    • 我知道使用By.css('.the-button'),但问题是如果有一组按钮,则很难识别每个按钮。那我们怎么能这样?如果有函数可以调用id就更好了。
    • 使用需要使用正确的选择器。您知道如何使用 css 选择特定按钮吗?这是基本的CSS东西。与 Angular 无关。 css 方法可以采用任何 css 选择器。如果你不确定如何做,那么你可以让它更容易,只需给按钮一个 id。然后你可以做css('#button-id')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多