0

Using jasmine and karma, I can pass the unit test using fake async and using a real event, but the coverage is not correct, the settimeout call back is ignored.

@Component({
  selector: 'slider',
  templateUrl: './slider.component.html',
  styleUrls: ['./slider.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [AgGridModule],
})
export class SliderComponent {
  otherMethod() {}
   
  onSliderReady() {
    window.addEventListener('resize', () => {
      setTimeout(() => {
        this.otherMethod();
      });
    });
  }
}

The unit test is working as expecting, the tick could be optional (not affecting the assertion).

  describe('onSliderReady', () => {
    it('should call otherMethod', fakeAsync(() => {
      spyOn(component, 'otherMethod')
      window.dispatchEvent(new Event('resize'));

      component.onSliderReady();
      tick(500);

      expect(component.otherMethod).toHaveBeenCalled();
    }));
  });

enter image description here

4
  • Do I understand your problem correctly: the test does not go into the otherMethod() via the onSliderReady() method? So the test "onSliderReady" fails? Commented Aug 29, 2024 at 5:33
  • the unit test is working as expected, the problem is that the pecentage of the file is very low because the settimeout is in red, Commented Aug 29, 2024 at 17:27
  • Ah you mean the test coverage. Sorry, I overlooked that Commented Aug 29, 2024 at 17:45
  • Yeah, test coverage, no problem, just looking this is very tricky Commented Aug 29, 2024 at 22:37

0

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.