Karma测试注入服务

时间:2017-04-02 00:51:15

标签: angular http service karma-runner

我尝试使用包含http post方法的注入服务来测试组件。但是当我运行测试时,karma会向我显示以下信息:

TypeError:无法读取属性'响应'未定义的

这是我的代码:

这是按钮和调用SignupService addUser方法的方法addUser调用的save方法:

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('xz@gmail.com');
   signup.get('passwordMatch').get('password').setValue('wis');
   signup.get('passwordMatch').get('confirmPassword').setValue('wis');
   let show = component.showModal;
   expect(show).toBeTruthy();
 });
});

任何人都可以帮助我吗?!

1 个答案:

答案 0 :(得分:0)

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

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