programing

각도 단위 테스트 입력 값

lastcode 2023. 8. 30. 21:45
반응형

각도 단위 테스트 입력 값

저는 유닛 테스트를 위해 공식 Angular2 문서를 읽고 있습니다(https://angular.io/docs/ts/latest/guide/testing.html) ). 하지만 구성 요소의 입력 필드 값을 설정하여 구성 요소 속성(bounding)에 반영되도록 하는 데 어려움을 겪고 있습니다.브라우저에서는 화면이 정상적으로 작동하지만 유닛 테스트에서는 필드 값을 설정할 수 없는 것 같습니다.

저는 아래 코드를 사용하고 있습니다.다른 테스트가 정상적으로 작동하므로 "filename"이 올바르게 초기화됩니다."comp"는 내 구성 요소의 인스턴스이며 입력 필드는 ngModel을 통해 "user.username"에 바인딩됩니다.

it('should update model...', async(() => {
    let field: HTMLInputElement = fixture.debugElement.query(By.css('#user')).nativeElement;
    field.value = 'someValue'
    field.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(field.textContent).toBe('someValue');
    expect(comp.user.username).toBe('someValue');
  }));

Angular2의 내 버전:"@angular/core": "2.0.0"

입력에는 textContent가 없고 값만 있습니다.expect(field.textContent).toBe('someValue');쓸모가 없습니다.그것이 아마도 실패하고 있는 것일 것입니다.하지만 두 번째 기대는 지나쳐야 합니다.여기 완전한 테스트가 있습니다.

@Component({
  template: `<input type="text" [(ngModel)]="user.username"/>`
})
class TestComponent {
  user = { username: 'peeskillet' };
}

describe('component: TestComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [ TestComponent ]
    });
  });

  it('should be ok', async(() => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      let input = fixture.debugElement.query(By.css('input'));
      let el = input.nativeElement;

      expect(el.value).toBe('peeskillet');

      el.value = 'someValue';
      el.dispatchEvent(new Event('input'));

      expect(fixture.componentInstance.user.username).toBe('someValue');
    });
  }));
});

중요한 부분은 첫 번째입니다.fixture.whenStable()발생하는 양식에 대한 비동기 설정이 있으므로 해당 설정이 완료된 후 완료될 때까지 기다려야 합니다.fixture.detectChanges()사용 중인 경우fakeAsync()대신에async()그러면 그냥 전화를 걸었을 것입니다.tick()끝나고fixture.detectChanges().

그냥 추가

fixture.detectChanges();

fixture.whenStable().then(() => {
  // here your expectation
})

고객의 기대/주장을 활용whenStable.then다음과 같은 기능:

component.label = 'blah';
fixture.detectChanges();

fixture.whenStable().then(() => {
    expect(component.label).toBe('blah');
}

@Input 컨텐츠로 유닛 테스트를 구현하려면 아래 코드를 수행합니다.

testing.component.ts

    import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-testing',
      templateUrl: `<app-input [message]='text'></app-input>`,
      styleUrls: ['./testing.component.css']
    })
    export class TestingComponent implements OnInit {
    public text = 'input message';
      constructor() { }
    
      ngOnInit() {
      }
    
    }

input.component.ts

    import { Component, OnInit, Input } from '@angular/core';
    
    @Component({
      selector: 'app-input',
      templateUrl: `<div *ngIf="message">{{message}}</div>`,
      styleUrls: ['./input.component.css']
    })
    export class InputComponent implements OnInit {
    @Input() public message: string;
      constructor() { }
    
      ngOnInit() {
        console.log(this.message);
      }
    
    }

input.component.spec.ts

    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    
    import { InputComponent } from './input.component';
    import { TestingComponent } from '../testing/testing.component';
    
    describe('InputComponent', () => {
      let component: InputComponent;
      let fixture: ComponentFixture<InputComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ InputComponent, TestingComponent ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(InputComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      it('should correctly render the passed @Input value', () => {
        component.message = 'test input';
        fixture.detectChanges();
        expect(fixture.nativeElement.innerText).toBe('test input');
      });
    
    });

언급URL : https://stackoverflow.com/questions/41063005/angular-unit-test-input-value

반응형