Угловой модульный тест: доступ к переменной шаблона
У меня есть этот код в шаблоне компонента, который открывает модальный 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 ответа
Вы можете использовать шпиона для слежки за функцией и проверки того, что было передано в качестве аргумента. Давайте предположим, что ваш компонент называется 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
переменная шаблона доступна из вашего компонента.
Сначала вы захотите добавить следующую строку в ваш компонент, чтобы вы могли ссылаться на переменную модального шаблона:
@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 для демонстрации.