首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Spectator setInput -如何传递对象

Angular Spectator setInput -如何传递对象
EN

Stack Overflow用户
提问于 2020-04-09 17:04:26
回答 1查看 804关注 0票数 2

也许是和this question一样的bug。

在我的旁观者测试中,我想测试将输入传递给组件:

sidebar.component.ts:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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()不能正常工作,但也许我只是忘了添加一些东西到我的设置中?

或者是我需要考虑的一些与异步管道相关的问题?

非常欢迎对测试设置中缺失或错误的内容提供任何其他提示,非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2020-04-13 06:15:22

在setInput之后,我建议您使用

代码语言:javascript
复制
spectator.detectChanges();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61117541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档