programing

단위 테스트 클릭 이벤트(Angular)

telebox 2023. 10. 9. 22:30
반응형

단위 테스트 클릭 이벤트(Angular)

Angular 2 앱에 유닛 테스트를 추가하려고 합니다.내 중 에가 있는 .(click)조련사 하면 사용자가 버튼을 클릭하면 에 정의된 함수가 호출됩니다에 정의됩니다..ts수업 파일 합니다.이 기능은 console.log 창에 버튼을 눌렀다는 메시지를 출력합니다.를 위한 console.log메시지:

describe('Component: ComponentToBeTested', () => {
    var component: ComponentToBeTested;

    beforeEach(() => {
        component = new ComponentToBeTested();
        spyOn(console, 'log');
    });

    it('should call onEditButtonClick() and print console.log', () => {
        component.onEditButtonClick();
        expect(console.log).toHaveBeenCalledWith('Edit button has been clicked!);
    });
});

합니다를 은할 때. 나는 단지 로깅이 발생하는 것을 테스트하고 싶지 않습니다.onEditButtonClick라고 합니다; 저는 또한 그것을 테스트하고 싶습니다.onEditButtonClick사용자가 구성 요소의 HTML 파일에 정의된 편집 버튼을 누르면 호출됩니다.내가 어떻게 그럴 수 있을까?

제 목표는 사용자가 편집 버튼을 클릭할 때 'onEditButtonClick'이 실행되는지 확인하는 것이고 출력되는 console.log만 확인하는 것이 아닙니다.

각도() 를를 .TestBed할 수 이렇게 하면 실제로 버튼을 잡고 클릭할 수 있습니다.입니다처럼 @NgModule을 위한 합니다.

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers: [  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  }));
});

그러면 당신은 그들을 감시해야 합니다.onEditButtonClick,합니다 method하고라고 합니다.

it('should', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  });
}));

여기서 우리는 실행해야 합니다.async다를 합니다.fixture.whenStable()

갱신하다

는 됩니다를 됩니다.fakeAsync/tickasync/whenStable 콤보로 후자는 다음과 같이 XHR 통화가 있는 경우 사용되어야 합니다.fakeAsync지원하지 않습니다.입니다처럼

it('should', fakeAsync(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();
  tick();
  expect(component.onEditButtonClick).toHaveBeenCalled();

}));

수입하시기 바랍니다.fakeAsync그리고.tick.

참고 항목:

이벤트는 다음을 사용하여 테스트할 수 있습니다.async/fakeAsync하는 기능'@angular/core/testing'에 /입니다.

는 입니다를 입니다.fakeAsync.

fakeAsync은 테스트 합니다.fakeAsync

클릭 이벤트에 의해 호출되는 메소드를 테스트합니다.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

아래는 Angular 문서가 말하는 내용입니다.

페이크 Async가 비동기화에 미치는 주요 이점은 테스트가 동기화된 것으로 보인다는 것입니다..then(...)눈에 보이는 통제의 흐름을 방해할 수 있습니다.약속의 귀환fixture.whenStable사라졌고, 대체되었습니다.tick()

한계가 있습니다.예를 들어, 당신은 XHR 콜을 a 내에서 할 수 없습니다.fakeAsync

Angular 6를 쓰고 있습니다.Mav55의 대답을 따랐더니 효과가 있었습니다.하지만, 저는 그들이fixture.detectChanges();꼭 필요해서 제거해봤는데도 되더라구요.그 다음에 제거했습니다.tick();효과가 있는지 확인해 보려고요마침내 나는 시험을 없앴습니다.fakeAsync()랩, 그리고 놀랍게도, 효과가 있었습니다.

그래서 결국 이렇게 됐습니다.

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

그리고 잘 작동했습니다.

버튼 호출 이벤트를 먼저 확인하려면 버튼 클릭 후에 호출될 메소드를 스파이로 처리해야 합니다. 그러면 첫 번째 행이 스파이온 스파이 메소드는 1) 구성 요소 이름 2) 메소드를 스파이로 처리해야 합니다.e: 'onSubmit'에서 '()'만 사용하지 않는 것을 기억하고 '()'만 필요한 이름을 클릭해야 합니다. 이제 클릭 이벤트를 추가할 이벤트 핸들러를 트리거해야 합니다. 그러면 우리 코드가 제출 방법을 한 번 호출합니다.

it('should call onSubmit method',() => {
    spyOn(component, 'onSubmit');
    let submitButton: DebugElement = 
    fixture.debugElement.query(By.css('button[type=submit]'));
    fixture.detectChanges();
    submitButton.triggerEventHandler('click',null);
    fixture.detectChanges();
    expect(component.onSubmit).toHaveBeenCalledTimes(1);
});

저도 비슷한 문제가 있어서(아래 자세한 설명) 해결했습니다(에서).jasmine-core: 2.52를 사용하여tick원래와 동일한(또는 더 큰) 밀리초의 함수setTimeout불러.

예를 들면, 내가 만약setTimeout(() => {...}, 2500);(2,500ms 이후에 트리거됨), 전화를 걸겠습니다.tick(2500), 그러면 문제가 해결될 겁니다

Delete(삭제) 버튼 클릭에 대한 반응으로 구성 요소에 있는 내용:

delete() {
    this.myService.delete(this.id)
      .subscribe(
        response => {
          this.message = 'Successfully deleted! Redirecting...';
          setTimeout(() => {
            this.router.navigate(['/home']);
          }, 2500); // I wait for 2.5 seconds before redirect
        });
  }

그녀는 나의 실무 시험입니다.

it('should delete the entity', fakeAsync(() => {
    component.id = 1; // preparations..
    component.getEntity(); // this one loads up the entity to my component
    tick(); // make sure that everything that is async is resolved/completed
    expect(myService.getMyThing).toHaveBeenCalledWith(1);
    // more expects here..
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
    deleteButton.click(); // I've clicked the button, and now the delete function is called...

    tick(2501); // timeout for redirect is 2500 ms :)  <-- solution

    expect(myService.delete).toHaveBeenCalledWith(1);
    // more expects here..
  }));

추신: 에 대한 훌륭한 설명.fakeAsync테스트의 일반적인 비동기는 여기에서 확인할 수 있습니다: Angular 2 - Julie Ralph와 함께 테스트 전략에 대한 비디오, 8시 10분부터 시작하여 4분 동안 :)

언급URL : https://stackoverflow.com/questions/40093013/unit-testing-click-event-in-angular

반응형