【发布时间】:2017-02-26 07:47:36
【问题描述】:
我可以使用
获取元素fixture.debugElement.query(By.css('h1'));
但是当我想通过类名获取元素时我应该怎么做。像这样的
fixture.debugElement.query(By.css('class="name"'))
【问题讨论】:
标签: unit-testing angular jasmine
我可以使用
获取元素fixture.debugElement.query(By.css('h1'));
但是当我想通过类名获取元素时我应该怎么做。像这样的
fixture.debugElement.query(By.css('class="name"'))
【问题讨论】:
标签: unit-testing angular jasmine
您使用By.css 传递一个css 选择器。因此,任何可以与 css 一起使用的选择器,都可以与 By.css 一起使用。一个类的选择器就是.classname(带句点)。
By.css('.classname') // get by class name
By.css('input[type=radio]') // get input by type radio
By.css('.parent .child') // get child who has a parent
这些只是一些例子。如果您了解 css,那么您应该知道如何使用选择器。
编辑:
要使用By.css(),请务必使用import { By } from '@angular/platform-browser';
【讨论】:
只是添加一些其他有用的选择元素的方法:
// get element with multiple classes
fixture.debugElement.query(By.css('.className1.className2'));
// get a certain element from a group of elements with the same class name
fixture.debugElement.queryAll(By.css('.className'))[1];
【讨论】:
Cannot find name 'By'.
我更喜欢你的 DOM 元素上的用户 ID,然后在 angular2 中对你进行单元测试 可以调用类似下面的东西来获取你想要的 DOM 元素的引用 并测试你喜欢什么。
//typscript syntax
fixture = TestBed.createComponent(<your component>);
let result = fixture.nativeElement.querySelector('<id attribute name of html element>');
expect(result.id).toEqual("id of your DOM element.").
希望对您有所帮助。
【讨论】:
确保 By 是从 @angular/platform-browser 而不是 protractor 导入的。
【讨论】:
基于布尔显示文本的示例测试用例:
it('should set title based on title flag from parent', () => {
component.title ="APP";
fixture.detectChanges();
const title = fixture.debugElement.query(By.css('label')).nativeElement;
expect(title.innerHTML).toContain('APP');
});
如果您从 .ts 文件更新标题,则必须使用 fixture.detectChanges()
【讨论】: