0

I have a page with sidebar section with sidebar-component and content section with a page-component. From the page-component, when I click a button, the sidebar-component toggles. Below is the code,

  async onSidebarButtonPressed() {
    const sidebar = document.querySelector('#filter-sidebar');
    console.log(sidebar);
    (sidebar as any)?.toggle();
  }

Now I want to cover the scenario where the

toggle()

is called. I tried stubing the sidebar-component,

  @Component({ selector: 'cf-wc-sidebar-filter-v9', template: '' })
    class SidebarStubComponent {
      toggle() { /* */}
    }
..
..
..


      it('should toggle sidebar action', async () => {
              const sidebarSpy= spyOn(document,'querySelector').and.callFake(()=>SidebarStubComponent);
   fixture.detectChanges();

  await component.onSidebarButtonPressed();

  });

I am getting an error "_a.toggle is not a function". Initially I tried with state and the tech guys told not to use state for this. I tried with @ViewChild and it comes undefined. Since these 2 components are completely disconnected

How else can I test this scenario?

Raajkumar
  • 857
  • 2
  • 13
  • 26
  • Querying the DOM directly is usually a code smell in Angular. One approach you could take here is to have a separate service to transmit the toggle message from the pageComponent to the sidebar – pjpscriv Oct 27 '21 at 04:09
  • OK. Is there any other way? – Raajkumar Oct 27 '21 at 04:12
  • The other way I would try to do it is use an `@Output` on the pageComponent to send an event up to the page and sidebar's shared parent and when you receive that event, you modify a variable that is an `@Input` on the sidebarComponent. Beyond that it's a bit hard to comment without seeing more of the code – pjpscriv Oct 27 '21 at 04:17
  • Side question, does `onSidebarButtonPressed` have to be `async`? – pjpscriv Oct 27 '21 at 04:18
  • OK. Will try both the options. Thanks. – Raajkumar Oct 27 '21 at 04:18
  • Hmmm not necessary, I was using it for state action dispatch. – Raajkumar Oct 27 '21 at 04:20

0 Answers0