0

I have an Input field in the UI

<input matInput placeholder="BLC" id='blc' formControlName="blc" (change)="onBLCChanged($event)" />

I want to do unit testing for this, but this field send $event not any value to the function, how can I mock this.

  it('some text', async(async() => {
    spyOn(component, 'onBLCChanged');
    // first round of change detection
    fixture.detectChanges();
    // get ahold of the input
    let input = debugElement.query(By.css('#blc'));
    let inputElement = input.nativeElement;

    //set input value
    inputElement.value = 'test';
    inputElement.dispatchEvent(new Event('change'));

    expect(component.onBLCChanged).toHaveBeenCalledWith({});
  }));

This is not working, Expected spy onBLCChanged to have been called with [ Object({ }) ] but actual calls were [ [object Event] ].

Please help, onBLCChanged is the method in the .ts file.

2 Answers 2

2

Try this-

it('some text', async(async() => {
      spyOn(component, 'onBLCChanged');
      // first round of change detection
      fixture.detectChanges();
      // get ahold of the input
      let input = debugElement.query(By.css('#blc'));
      let inputElement = input.nativeElement;

      //set input value
      inputElement.value = 'test';

      // save event object so that you can do comparison.
      const event = new Event('change');
      inputElement.dispatchEvent(event);

      expect(component.onBLCChanged).toHaveBeenCalledWith(event);
    }));
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

 it('some text', async(async() => {
    const spyOnFunction = spyOn(component, 'onBLCChanged');
    // first round of change detection
    fixture.detectChanges();
    // get ahold of the input
    let input = debugElement.query(By.css('#blc'));
    let inputElement = input.nativeElement;

    //set input value
    inputElement.value = 'test';
    inputElement.dispatchEvent(new Event('change'));

    expect(spyOnFunction).toHaveBeenCalled();
  }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.