-1

I have a component say Test.component. Here is the HTML of Test.component:

<app-anothercomponent [myProperty]="true" (myMethod)="doWork($event)"> </app-anothercomponent>

I want to write a test/spec to check whether Test.component is rendered with app-anothercomponent with myMethod property wired. i.e if the component has this code:

  <app-anothercomponent [myProperty]="true"> </app-anothercomponent>

it should fail as myMethod method is not wired.

I have figured out the way to detect the property being rendered there but not the method, i.e I can detect whether myProperty with the following code:

  it('should render app-anothercomponent with #myProperty true', () => {
    // Arrange
    const compiled = fixture.debugElement.nativeElement;
    const selector = compiled.querySelector('app-anothercomponent');

    // Assert

    expect(selector.myProperty).toBe(true);
  });

I am trying to figure out how to write a similar spec like that to make sure myMethod method wiring is present there.

  • Does this answer your question? [Unit testing click event in Angular](https://stackoverflow.com/questions/40093013/unit-testing-click-event-in-angular) plz check Mav55 answer – Naren Murali Dec 08 '22 at 06:29

1 Answers1

0

Naren is right but to make it explicit to show you what to do, try the following:

it('should call do work', () => {
    const component = fixture.debugElement.query(By.css('app-anothercomponent'));
     
    const doWorkSpy = spyOn(component, 'doWork');
    // !! The first argument is the event you would like to trigger
    // The 2nd argument is the value of $event (can be anything, object, array, string).
    component.triggerEventHandler('myMethod', 'hello');
    
    expect(doWorkSpy).toHaveBeenCalledWith('hello');
  });
AliF50
  • 16,947
  • 1
  • 21
  • 37