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())
后,我将数据放入了我的回调中