Угловой модульный тест: доступ к переменной шаблона - PullRequest
0 голосов
/ 08 января 2019

У меня есть этот код в шаблоне компонента, который открывает модал ngx-bootstrap:

<button type="button"
        class="btn btn-primary"
        (click)="onOpenSharesModal(modal)">Click me!</button>
<ng-template #modal>
    <app-modal (closed)="onCloseSharesModal()"></app-modal>
</ng-template>

Компонент:

onOpenSharesModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-lg' });
}

Тест:

it('should call onOpenSharesModal() when button clicked', () => {
  const button = fixture.debugElement.query(By.css('button'));
  const spy = spyOn(component, 'onOpenSharesModal');

  button.triggerEventHandler('click', null);
  fixture.detectChanges();

  expect(spy).toHaveBeenCalled();
});

Я пытаюсь проверить компонент: я смог проверить, что вызывается onOpenSharesModal(), но я бы хотел проверить, вызывался ли он с переменной шаблона modal в качестве аргумента. Как я могу это сделать?

Ответы [ 2 ]

0 голосов
/ 08 января 2019

Сначала вы захотите добавить следующую строку в ваш компонент, чтобы вы могли ссылаться на переменную модального шаблона:

@ViewChild('modal') myModal: TemplateRef<any>; // for testing

Теперь вы можете ссылаться на переменную компонента myModal в вашем тесте:

it('should call onOpenSharesModal() when button clicked', () => {
  const button = fixture.debugElement.query(By.css('button'));
  const spy = spyOn(component, 'onOpenSharesModal');

  button.triggerEventHandler('click', null);
  fixture.detectChanges();

  expect(spy).toHaveBeenCalled();
  expect(spy).toHaveBeenCalledWith(component.myModal);
});

Вот рабочий StackBlitz для демонстрации.

0 голосов
/ 08 января 2019

Вы можете использовать шпиона, чтобы шпионить за функцией и проверять то, что было передано в качестве аргумента. Давайте предположим, что ваш компонент называется MyComponent. В вашем файле модульного теста у вас есть (немного укороченный, но вы должны получить изображение):

let myComponent: MyComponent = fixture.componentInstance;

// Set up a spy on your function
let spy = spyOn(myComponent, 'onOpenSharesModal').and.callThrough();

// After the function has been called somewhere in your component
expect(spy).toHaveBeenCalled();

// Check the arguments that were passed
expect(spy.calls.mostRecent().args[0]).toEqual(myComponent.modal);

Предполагается, что переменная шаблона modal доступна из вашего компонента.

...