1

I fairly new in Angular and TDD. Currently,I am trying to test an function on which it is called during an a resize event. Here is my following code:

header.component.ts

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss'],
    host: {
        '(window:resize)': 'onResize($event)'
    }
})
export class HeaderComponent implements OnInit {
    isDesktop = window.innerWidth > 768;
    menuOpen = false;

    constructor() {}

    ngOnInit() {}

    onResize(event) {
        this.isDesktop = event.target.innerWidth > 768;
        this.menuOpen = !this.isDesktop && this.menuOpen;
    }
}

header.component.ts

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ HeaderComponent,SideMenuComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  })

  it('should trigger onResize method when window is resized', () => {
    const spyOnResize = spyOn(component, 'onResize');
    window.dispatchEvent(new Event('resize'));
    expect(spyOnResize).toHaveBeenCalled();
  });

When I run the tests it outputs the test failed saying _<spyOn> : could not find an object to spy upon. Are there any ideas or clues to fix this problem? Any help is greatly appreciated Thank you.

PikaDude
  • 31
  • 4
  • https://stackoverflow.com/questions/40106801/spyon-could-not-find-an-object-to-spy-upon-for-start/40109595 take a look at this answer. – Developer Nov 07 '19 at 12:48

1 Answers1

0

You could try this. you can return the inner width from a method and mock that method to return different values

https://emailtoanees.medium.com/angular-unit-test-window-innerwidth-c523d2e64eaf

aneeshere
  • 509
  • 5
  • 16