我已经使用 angular2
创建了一个登录页面。它有两个输入字段,分别是userName
和password
。该登录名中有一个按钮。
当我要为 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
});
我将通过提供输入值进行测试,然后单击登录按钮,看看接下来会发生什么。
我找不到正确的教程来正确使用谓词。
最佳答案
创建 Predicate
的最简单方法是使用 By
之一静态方法,即 css
、directive
。
const button = fixture.debugElement.query(By.css('.the-button')).nativeElement;
By.css
让您传递任何 css 选择器。 query
的结果将是一个 DebugElement
,因此如果您想与 native DOM 元素交互,您需要获取 nativeElement
。
关于angular - 如何在angular2中使用谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563647/