2017-08-30 67 views
0

更新模型的問題,我偶然發現翻過一個奇怪的問題。我正在使用基於模板的表單和雙向綁定進行單元測試。這裏是測試代碼:角4的單元測試形式與雙向綁定。從圖

describe('Template Forms Input',() => { 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [BrowserModule, FormsModule], 
     declarations: [DummyFormsComponent], 
    }).compileComponents(); 
    }); 

    it('DOM input value changes the component model', fakeAsync(() => { 

    const fixture = TestBed.createComponent(DummyFormsComponent); 
    fixture.detectChanges(); 
    const dummyInputDe = fixture.debugElement.query(By.css('input')); 
    const dummyInputEl = dummyInputDe.nativeElement; 

    dummyInputEl.value = 'Super dummy'; 
    dummyInputEl.dispatchEvent(new Event('input')); 

    tick(); 
    fixture.detectChanges(); 

    expect(fixture.debugElement.query(By.css('h2')).nativeElement.textContent).toEqual('Super dummy'); 
    })); 
}); 

@Component({ 
    selector: 'dummy-forms', 
    template: ` 
    <form> 
     <input name="title" [(ngModel)]="model.anotherDummyValue"> 
    </form> 
    <h2>{{model.anotherDummyValue}}</h2> 
    ` 
}) 
class DummyFormsComponent { 

    model = { anotherDummyValue: '', date: '' }; 
} 

而且我無法通過測試。 h2總是空的。然而。如果我刪除<form>標籤,只保留輸入在視圖中。測試通過。

我覺得我做錯了什麼與異步行爲。有人會有一個想法嗎?

回答

0

嘗試在你的代碼添加組件實例。更多的是我沒有看到你的組件中的ngOnInit或構造函數。

component = fixture.componentInstance;

我們一般做以下方式

describe('EditComponent',() => { 
    let component: EditComponent; 
    let fixture: ComponentFixture<EditComponent>; 
    let displayText: DebugElement; 
    let editableText: DebugElement; 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     imports: [ 
     FormsModule, 
     ReactiveFormsModule 
     ], 
     declarations: [ EditComponent, MockCkeditorComponent ] 
    }).compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(EditComponent); 
    component = fixture.componentInstance; 
    component.text = 'test input in the editor'; 
    displayText = fixture.debugElement.query(By.css('.row')); 
    editableText = fixture.debugElement.query(By.css('.editor-form')); 
    }); 

    it('should be created',() => { 
    component.ngOnInit(); 
    fixture.detectChanges(); 
    expect(component).toBeTruthy(); 
    }); 
.... 

在beforeEach declar您的組件。