也许是像这个问题一样的错误。。。
在我的旁观者测试中,我想测试将输入传递给组件:
sidebar.component.ts:
export class SidebarComponent {
@Input() projects: Project[];
filteredProjects: Observable<Project[]>;
constructor() {
this.filteredProjects = this.searchControl.valueChanges.pipe(
startWith(''),
map(project =>
project ? this.filterProjects(project) : this.projects.slice()
)
);
}
private filterProjects(value: string): Project[] {
const filterValue = new RegExp(value.toLowerCase().trim());
return this.projects.filter(
project => filterValue.test(project.name.toLowerCase())
);
}
}
sidebar.component.html:
<div class="sidebar__header--count">
<span>Projects</span> ({{ (filteredProjects | async).length }})
</div>
<mat-nav-list>
<a
data-test-sidebar-nav-list-item
class="nav__list--item"
mat-list-item
routerLinkActive="active"
routerLink="/project/{{ project.id }}"
*ngFor="let project of filteredProjects | async"
>
<div class="project">
<div class="project__name">{{ project.name }}</div>
</div>
</a>
</mat-nav-list>
sidebar.component.spec.ts:
describe('SidebarComponent', () => {
const createComponent = createComponentFactory({
component: SidebarComponent,
imports: [ ... ]
});
let component: any;
let spectator: Spectator<SidebarComponent>;
beforeEach(() => {
spectator = createComponent();
component = spectator.component;
});
it('should create', () => {
expect(component).toBeTruthy(); // works
});
it('should initially show all projects', () => {
spectator.setInput({
projects: {
FOO1: { id: 1, name: 'foo' },
FOO2: { id: 2, name: 'foo' }
FOO3: { id: 3, name: 'foo' }
}
});
/* count items from list */
const navItem = spectator.query('[data-test-sidebar-nav-list-item]');
console.log(navItem); // is null, but should not be null
const itemHeader = spectator.query('.sidebar__header--count'); // null returned, but should be a HTML element
expect(itemHeader.innerHTML).toContain('Projects (3)');
});
});
我只是假设setInput()
不能正常工作,但也许我只是忘记了要添加到我的设置中的内容?
或者可能是我需要考虑的与异步管道有关的一些问题?
非常欢迎测试设置中遗漏或错误的任何其他提示,非常感谢。
在setInput之后,我建议您使用
spectator.detectChanges();