Я пытаюсь написать модульные тесты для компонента, использующего MediaQueryList. Я изо всех сил пытаюсь охватить одну строку, которая назначает функцию стрелки переменной.
Я пробовал отслеживать метод внутри функции, но получаю сообщение об ошибке, что метод никогда не вызывался.
Мои занятия:
export class AppComponent implements OnDestroy {
mobileQuery: MediaQueryList;
_mobileQueryListener: () => void;
constructor(
private changeDetectorRef: ChangeDetectorRef,
private media: MediaMatcher
) {
this.mobileQuery = this.media.matchMedia('(max-width: 1000px)');
this._mobileQueryListener = () => this.changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this._mobileQueryListener);
}
ngOnDestroy(): void {
this.mobileQuery.removeListener(this._mobileQueryListener);
}
}
Мой тест:
it('should setup the media query', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.mobileQuery).toBeTruthy();
expect(app._mobileQueryListener).toEqual(/* ??? */);
});
Я хочу достичь 100% покрытия кода, и для этого мне нужно покрыть назначение _mobileQueryListener. Есть идеи?





Я думаю, вы должны попробовать проверить:
it('should setup the media query', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.mobileQuery).toBeTruthy();
expect(app._mobileQueryListener).toBeDefined();
});
_mobileQueryListener: () => void; — это просто объявление, а не инициализация переменной. Итак, проверьте, определено ли оно.
и чтобы проверить поведение _mobileQueryListener для вызова detectChanges(), вы можете добавить еще один тестовый пример (убедитесь, что у вас есть public changeDetectorRef, чтобы поместить spy над ним):
it('should should call "detectChanges()" from "_mobileQueryListener"', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app._mobileQueryListener).toBeDefined();
spyOn(app.changeDetectorRef,"detectChanges").and.callThrough();
app._mobileQueryListener();
expect(app.changeDetectorRef.detectChanges).toHaveBeenCalled();
});
Кстати, переместите код ниже в блок beforeEach() и объявите эти переменные глобально.
fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;