Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 业力回调总是未定义的_Unit Testing_Angular_Karma Jasmine - Fatal编程技术网

Unit testing 业力回调总是未定义的

Unit testing 业力回调总是未定义的,unit-testing,angular,karma-jasmine,Unit Testing,Angular,Karma Jasmine,在对我的服务进行单元测试时,我遇到了一个问题 这是我的测试用例 it("updateUserProfile() should update user profile", async(() => { mockBackend.connections.subscribe((connection: MockConnection) => { let responseOpts = new ResponseOptions({ body: JSON.stringify({ username: "

在对我的服务进行单元测试时,我遇到了一个问题 这是我的测试用例

it("updateUserProfile() should update user profile", async(() => {
 mockBackend.connections.subscribe((connection: MockConnection) => {
 let responseOpts = new ResponseOptions({ body: JSON.stringify({ username: "testuser" }) });
  connection.mockRespond(new Response(responseOpts));
 });
 let obj = {
  callback: (r) => {
    expect(r.username).toBe("testuser");
  }
 };
 spyOn(obj, "callback").and.callThrough();
 service.updateUserProfile({}, obj.callback);
 expect(obj.callback).toHaveBeenCalled();
}));
这是我的服务

updateUserProfile(user: Profile, callback?: Function): void {
 let sub = this.http.patch(url, user, { headers: this.getHeaders() }).subscribe(r => {
   callback(r);
   if (sub) sub.unsubscribe();
 });
}

在这种情况下,它工作正常。我的
spy
返回true,即已启动回调,但我的
回调中的代码始终未定义。我还想测试响应。

我找到了问题的解决方案

updateUserProfile(user: Profile, callback?: Function): void {
 let sub = this.http.patch(url, user, { headers: this.getHeaders() }).subscribe(r => {
   callback(r.json());
   if (sub) sub.unsubscribe();
 });
}

我在调用
callback
时没有将响应解析为json,它至少应该调用我的
callback
和response。将
callback(r)
更改为
callback(r.json())
后,我将数据放入了回调中。

我找到了问题的解决方案

updateUserProfile(user: Profile, callback?: Function): void {
 let sub = this.http.patch(url, user, { headers: this.getHeaders() }).subscribe(r => {
   callback(r.json());
   if (sub) sub.unsubscribe();
 });
}
我在调用
callback
时没有将响应解析为json,它至少应该调用我的
callback
和response。将
callback(r)
更改为
callback(r.json())
后,我将数据放入了我的回调中