2017-04-02 106 views
0

我想要測試一個包含一個http post方法的注入服務的組件。但是當我運行測試業報顯示我下面的消息:Karma測試注入服務

類型錯誤:無法讀取的不確定

財產「響應」這是我的代碼:

這是保存方法是由按鈕,並且所述方法ADDUSER調用該SignupService ADDUSER方法調用:

save() { 
this.addUser(); 
this.onShowModal(); 


} 

    private addUser(){ 
    // Copy the form values over the product object values 
    let user = Object.assign({}, this.customer, this.signUpForm.value); 
    this.signUpService.addUser(user).subscribe((result) =>   this.onSaveComplete(result), 
    (error: any) => this.errorMessage = <any>error); 
    this.modalMessage = this.errorMessage 


} 

這是叔他SignupService ADDUSER方法:

addUser (user : Customer){ 
let headers = new Headers({ 'Content-Type': 'application/json' }); 
let options = new RequestOptions({ headers: headers }); 
return this.http.post(this.url,user,options) 
    .map(this.extractResponseData) 
    .do(data => console.log('Add user : ' + JSON.stringify(data))) 
    .catch(this.handleError); 

private handleError(error: Response) { 
return Observable.throw(error.json().error || 'Server error');} 



private extractResponseData(response: Response){ 
let body = response.json(); 
console.log(body.data); 
return body.data || {}; 

}

,最後,這是我的天賦是處理錯誤:

it('should save the user submetted',() => { 
    component.save(); 
    let signup = component.signUpForm; 
    signup.get('firstName').setValue('BEN'); 
    signup.get('secondName').setValue('wis'); 
    signup.get('username').setValue('wiss013'); 
    signup.get('email').setValue('[email protected]'); 
    signup.get('passwordMatch').get('password').setValue('wis'); 
    signup.get('passwordMatch').get('confirmPassword').setValue('wis'); 
    let show = component.showModal; 
    expect(show).toBeTruthy(); 
}); 
}); 

任何一個可以幫助我嗎?!

+0

如果你測試一個組件,然後模擬一個服務。如果你測試一個服務,模擬一個http請求。一次只能測試一個單元。 – estus

+0

感謝您的回覆,但它仍然無法正常工作並給出相同的錯誤,我認爲我的規範無法識別ExtractResponseData函數中的響應模塊。這些都在規格文件導入模塊:'beforeEach(異步(()=> { TestBed.configureTestingModule({ 聲明:[SignUpComponent], 進口:[FormsModule,BrowserModule,ReactiveFormsModule, ModalModule.forRoot(), HttpModule], 提供程序:[SignUpService,Http,ConnectionBackend] }) .compileComponents(); })); ' –

回答

0
describe('Test you service',() => { 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     providers: [YOUR_SERVICE] 
    }); 
    }); 

    it('hashCode should return correct hash code', inject([YOUR_SERVICE], (service: YOUR_SERVICE) => { 
    .... 
    })); 
}); 
相關問題