Как получить компоненты пользовательского интерфейса в Angular 8 - PullRequest
0 голосов
/ 18 марта 2020

Я использую свой собственный созданный компонент. Что app-button.ts делает так, что проверяет текущие роли пользователя и затем отображает, соответствуют ли они определенным ролям.

ButtonType просто определяет, какой стиль использовать.

demo.ts:

  <app-button
  buttonText="BACK"
  (clickEvent)="goBack()"
  [buttonType]="'secondary'"
  >
  </app-button>

Реализация кнопки кнопки приложения:

<button *ngIf="canRender" class="{{ buttonClass }}" (click)="onClickEvent()" [disabled]="disabled">
  <span class="{{ spanClass }}">{{ buttonText }}</span>
</button>

Файл app-button.ts:

export class PrimaryButtonComponent implements OnInit {
  @Input() buttonText: string;
  @Input() disabled? = false;
  @Input() allowedRoles: Role[] = [];
  @Input() buttonType = 'primary';

  canRender? = false;

  buttonClass: string;
  spanClass: string;

  @Output() clickEvent = new EventEmitter();

  constructor(private credentialsService: CredentialsService) {}

  ngOnInit() {
    if (this.allowedRoles.length !== 0) {
      const currentUserRoles: Role[] = this.credentialsService.currentUserValue.role.slice();

      this.canRender = allowedToAccess(this.allowedRoles, currentUserRoles);
    } else {
      this.canRender = true;
    }

    if (this.buttonType === 'primary') {
      this.buttonClass = 'primary-button';
      this.spanClass = 'primary-button-text';
    }

    if (this.buttonType === 'secondary') {
      this.buttonClass = 'secondary-button';
      this.spanClass = 'secondary-button-text';
    }
  }

  onClickEvent() {
    this.clickEvent.emit();
  }
}

Юнит-тест:

fit('should navigate back to dashboard when click back button', async(() => {
    const onClickSpy = spyOn(component, 'goBack').and.callThrough();
    const routerSpy = spyOn(router, 'navigate');

    // Click Back button
    const button = fixture.debugElement.query(By.css('.secondary-button'));

    expect(button).not.toBeNull();
  }));

, когда я выполняю свой юнит-тест, я вижу эту ошибку

Error: Expected null not to be null.

Но мой фактический пользовательский интерфейс показывает компонент. как это может быть нулевым в тесте?

1 Ответ

0 голосов
/ 18 марта 2020

В TestBed.configureTestingModule, в массиве declarations добавьте ButtonComponent (при условии, что ButtonComponent - это то, что называется классом). После этого expect(button).not.toBeNull(); должно быть хорошо до go.

...