Angular Зритель setInput - как передать объект - PullRequest
1 голос
/ 09 апреля 2020

Возможно, это та же ошибка, что и этот вопрос ...

В моем тесте для зрителей я хочу проверить передачу входных данных компоненту:

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.spe c .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() не работает правильно, но, может быть, я просто забыл что-то добавить в мои настройки?

Или это могут быть некоторые проблемы, связанные с асин c конвейером, которые я должен рассмотреть?

Любые другие советы о том, чего не хватает или что не так в тестовой настройке, приветствуются, большое спасибо.

1 Ответ

0 голосов
/ 13 апреля 2020

После setInput, я предлагаю вам использовать

spectator.detectChanges();
...