source

setTimeout()이 포함된 함수를 테스트합니다.

itover 2023. 8. 5. 22:20
반응형

setTimeout()이 포함된 함수를 테스트합니다.

구성 요소에 다음이 포함된 근접 기능이 있습니다.setTimeout()애니메이션이 완료될 시간을 주기 위해.

public close() {
    this.animate = "inactive"
    setTimeout(() => {
       this.show = false
    }, 250)
}

this.show에 구속되어 있습니다.ngIf.

this.animate애니메이션에 바인딩되어 있습니다.

이 기능을 테스트해야 하는 테스트가 있습니다.

it("tests the exit button click", () => {
  comp.close()
  fixture.detectChanges()
  //verifies the element is no longer in the DOM
  const popUpWindow = fixture.debugElement.query(By.css("#popup-window"))
  expect(popUpWindow).toEqual(null)
})

다음이 있을 때 이 기능을 적절하게 테스트하는 방법은 무엇입니까?setTimeout()?

사용하고 있었습니다.jasmine.clock().tick(251)하지만 창문은 절대 사라지지 않을 겁니다이것에 대해서도 의견이 있으십니까?

다음 두 가지 중 하나를 수행할 수 있습니다.

1: 실제로 테스트에서 250ms+1ms를 기다립니다.setTimeout()그런 다음 요소가 실제로 사라졌는지 확인합니다.

2: 사용fakeAsync()그리고.tick()시험에서 시간을 시뮬레이션하는 것tick()원본의 setTimeout을 해결합니다.close()그리고 검사는 나중에 바로 일어날 수 있습니다.fixture.whenStable().then(...).

예:

it("tests the exit button click", fakeAsync(() => {
  comp.close()
  tick(500)
  fixture.detectChanges()

  fixture.whenStable().then(() => {
    const popUpWindow = fixture.debugElement.query(By.css("#popup-window"))
    expect(popUpWindow).toBe(null)
  })
}))

원래의 방법을 기다리는 것보다 훨씬 더 빠르기 때문에 두 번째 방법을 사용하는 것을 제안합니다.여전히 첫 번째를 사용하는 경우 테스트 전에 시간 초과 시간을 줄여 더 빨리 실행되도록 합니다.

서비스

전화를 걸 필요가 없는 서비스의 경우detectChanges끝나고tick그리고 기대문을 안으로 묶을 필요가 없습니다.whenStable당신은 당신의 논리를 바로 할 수 있습니다.tick.

  it('should reresh token after interval', fakeAsync(() => {
    // given
    const service: any = TestBed.get(CognitoService);
    const spy = spyOn(service, 'refreshToken').and.callThrough();
    ....
    // when
    service.scheduleTokenRefresh();
    tick(TOKEN_REFRESH_INTERVAL);
    // then
    expect(spy).toHaveBeenCalled();
  }));

내 구성요소에서 방법은 다음과 같습니다.

hideToast() {
    setTimeout( () => {
      this.showToast = false;
    }, 5000);
  }

이에 대한 테스트(댓글로 설명):

it('should hide toast', () => {
  component.showToast = true; // This value should change after timeout
  jasmine.clock().install();  // First install the clock
  component.hideToast();      // Call the component method that turns the showToast value as false
  jasmine.clock().tick(5000); // waits till 5000 milliseconds
  expect(component.showToast).toBeFalsy();  // Then executes this
  jasmine.clock().uninstall(); // uninstall clock when done
});

이것이 도움이 되길 바랍니다!!

방금 제 프로젝트와 작업에서 이것을 시도했습니다.

jasmine.clock().tick(10);

저는 OP의 설정과 섬뜩할 정도로 비슷한 방법이 있어서 제가 생각하기에 훨씬 더 간단한 테스트를 추가하려고 합니다.

방법 **

public close() {
    this.animate = "inactive"
    setTimeout(() => {
       this.show = false
    }, 250)
}

재스민 테스트 **

it('should set show to "false" after 250ms when close is fired', (done) => {
      component.close();
      setTimeout(() => {
        expect(component.close).toBeFalse();
        done();
      }, 251);
    });

테스트가 완료되었음을 재스민에게 알리기 위해 'done'을 사용하고 내 메소드의 setTimeout 후 setTimeout에 1ms를 추가하여 실행합니다.

@Kailas가 언급한 이 솔루션은 저에게 적합합니다.

hideToast() {
    setTimeout( () => {
      this.showToast = false;
    }, 5000);
  }

it('should hide toast', () => {
  component.showToast = true; // This value should change after timeout
  jasmine.clock().install();  // First install the clock
  component.hideToast();      // Call the component method that turns the showToast value as false
  jasmine.clock().tick(5000); // waits till 5000 milliseconds
  expect(component.showToast).toBeFalsy();  // Then executes this
  jasmine.clock().uninstall(); // uninstall clock when done
});

그러나 다음 오류가 발생할 수 있습니다.

오류: Jasmine Clock이 사용자 지정 글로벌 타이머 기능을 통해 설치할 수 없습니다. 시계가 이미 설치되었습니까?

이 문제를 해결하려면 먼저 시계를 제거해야 합니다.

it('should hide toast', () => {
  jasmine.clock().uninstall()
  component.showToast = true; 
  jasmine.clock().install();  
  component.hideToast();      
  jasmine.clock().tick(5000); 
  expect(component.showToast).toBeFalsy();  
  jasmine.clock().uninstall(); 
});

언급URL : https://stackoverflow.com/questions/41772989/test-a-function-that-contains-a-settimeout

반응형