对于html:
<div id="shan">Hey there</div>
- fixture.debugElement.query(By.css('#hello'))
用于获取 DOM 对象的“DebugElement”。更多信息可以找到here in offical doc。您可以将id 传递为By.css('#hello'),class 传递为By.css('.hello'),或者您也可以使用By.css('div') 或By.css('some-app-component') 等方式传递元素
DebugElement 是一个 Angular 类,其中包含与调查元素或组件
相关的各种引用和方法
fixture.debugElement.query(By.css('#shan'))
会回来
DebugElement__PRE_R3__{listeners: [], parent: DebugElement__PRE_R3__{listeners: [], parent: null, debugContext: DebugContext{view: ..., nodeIndex: ..., nodeDef: .. ., elDef: ..., elView: ...}, nativeNode: 你好,属性:Object{},属性:Object{ng-version: ...},类:Object{},样式:Object{} , childNodes: [...], nativeElement: Hey there}, debugContext: DebugContext{view: Object{def: ..., parent: ..., viewContainerParent: ..., parentNodeDef: ...,上下文:...,组件:...,节点:...,状态:...,根:...,渲染器:...,oldValues:...,一次性用品:.. ., initIndex: ...}, nodeIndex: 0, nodeDef: Object{nodeIndex: ..., parent: ..., renderParent: ..., bindingIndex: ..., outputIndex: ..., checkIndex: 。 ..,标志:...,childFlags:...,directChildFlags:...,childMatchedQueries:...,matchedQueries:...,matchedQueryIds:...,引用:...,ngContentIndex:... ,childCount:...,绑定:...,bindingFlags:...,输出:...,元素:...,提供者:.. ., text: ..., query: ..., ngContent: ...}, elDef: Object{nodeIndex: ..., parent: ..., renderParent: ..., bindingIndex: ..., outputIndex :...,checkIndex:...,标志:...,childFlags:...,directChildFlags:...,childMatchedQueries:...,matchedQueries:...,matchedQueryIds:...,引用:。 ..,ngContentIndex:...,childCount:...,绑定:...,bindingFlags:...,输出:...,元素:...,提供者:...,文本:... , 查询: ..., ngContent: ...}, elView: Object{def: ..., parent: ..., viewContainerParent: ..., parentNodeDef: ..., context: ..., 组件: ...,节点:...,状态:...,根:...,渲染器:...,oldValues:...,一次性:...,initIndex:...}},nativeNode:嘿那里,属性:Object{},属性:Object{id:'shan'},类:Object{},样式:Object{},childNodes:[DebugNode__PRE_R3__{listeners:...,parent:...,_debugContext : ...,
..nativeNode:...}],nativeElement:嘿,名字:'div'}
- fixture.debugElement.nativeElement.querySelector('#hello')
nativeElement 返回对 DOM 元素的引用,如上所述,该元素也可以位于 debugElement 之下。您可以在测试用例中使用它执行诸如 click() 事件之类的操作。
fixture.debugElement.nativeElement.querySelector('#hello').click(); // this will create a click event over this element.
它适用于查询class
(fixture.debugElement.nativeElement.querySelector('.hello')) 和 id 之类的东西。
fixture.debugElement.nativeElement.querySelector('#shan')
会回来
<div _ngcontent-a-c0="" id="shan">Hey there</div>
- document.getElementById('hello')
这是我们访问id(不是class)的好方法。您无法通过类似的操作访问class
document.getElementById('.hello') // will return null
另外,请注意,您不需要在此函数参数中传递 #。
document.getElementById('#hello') // will return null
在使用 angular 时应该避免使用它,因为 Angular 有自己的 ChangeDetection,这需要它与 fixtures 一起使用。通过直接调用document,你最终会撞到墙上,试图弄清楚为什么元素会以null 出现
document.getElementById('shan')
会回来
<div _ngcontent-a-c0="" id="shan">Hey there</div>
Since you are new to unit testing in angular, you can refer my series of articles on Unit testing 。我希望这能帮到您。干杯!