2017-04-02 110 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) => { 
    .... 
    })); 
});