我目前正在整理一些在组件级别上测试Angular 2应用程序的最佳实践.
我已经看过一些教程查询fixture的NativeElement对象的选择器等,例如
it('should render "Hello World!" after click', async(() => {
builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
fixture.detectChanges();
let el = fixture.nativeElement;
el.querySelector('h1').click();
fixture.detectChanges();
expect(el.querySelector('h1')).toHaveText('Hello World!');
});
}));Run Code Online (Sandbox Code Playgroud)
但是,在juliemr的Angular 2测试种子中,她通过父DebugElement对象访问NativeElement.
it('should render "Hello World!" after click', async(() => {
builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
compiled.querySelector('h1').click();
fixture.detectChanges();
expect(compiled.querySelector('h1')).toHaveText('Hello World!');
});
}));Run Code Online (Sandbox Code Playgroud)
是否有任何特定情况你会在其nativeElement上使用fixture的debugElement.nativeElement?
我的项目中有一个组件调用一个服务来检索一些(本地存储的)JSON,它被映射到一个对象数组并返回给要显示的组件.我遇到的问题是视图中的绑定似乎在我第一次调用服务时没有更新,但是第二次调用服务时会更新.
组件模板:
@Component({
selector: 'list-component',
template: `
<button type="button" (click)="getListItems()">Get List</button>
<div>
<table>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Job Title
</th>
</tr>
<tr *ngFor="let employee of _employees">
<td>
{{employee.id}}
</td>
<td>
{{employee.name}}
</td>
<td>
{{employee.jobTitle}}
</td>
</tr>
</table>
</div>
`,
changeDetection: ChangeDetectionStrategy.Default
})
Run Code Online (Sandbox Code Playgroud)
组件控制器类:
export class ListComponent {
_employees: Employee[];
constructor(
private employeeService: EmployeeService
) {
}
getListItems() {
this.employeeService.loadEmployees().subscribe(res => {
this._employees = res;
});
}
}
Run Code Online (Sandbox Code Playgroud)
和服务:
@Injectable()
export class EmployeeService {
constructor(
private http: …Run Code Online (Sandbox Code Playgroud)