尝试进行测试,但收到此错误消息:
预期对象是一种Object,但是状态为Response: URL为null null:
知道这里缺少什么吗?
login.component.ts:
loginEvent(username, passw) {
let obj = {
user: username,
pass: passw
};
if (this.validation(obj)) {
this.httpService.loginPostToServer(obj).subscribe(
(response) => this.saveTokenToLocalstorage(response),
(error) => console.log(error)
);
}
};
http.service.ts:
loginPostToServer(data) {
return this.http.post(this.url + 'login', data);
}
测试:
import { async, TestBed, inject } from '@angular/core/testing';
import { HttpModule, Http, ResponseOptions, Response, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { HttpService } from './http.service';
describe('HttpService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ HttpService, MockBackend, BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}],
imports: [ HttpModule ]
});
});
it('should be created', inject([HttpService], (service: HttpService) => {
expect(service).toBeTruthy();
}));
it('should construct', async(inject(
[HttpService, MockBackend], (service, mockBackend) => {
expect(service).toBeDefined();
})));
describe('loginPostToServer', () => {
const mockResponse = {
success: true,
token: "sample token",
user: "john"
};
const fakeUser = {
user: "john",
pass: "1234"
};
it('should parse response', async(inject(
[HttpService, MockBackend], (service, mockBackend) => {
mockBackend.connections.subscribe(conn => {
conn.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockResponse) })));
});
const result = service.loginPostToServer(fakeUser);
result.subscribe(res => {
expect(res).toEqual({
success: true,
token: "sample token",
user: "john"
});
});
})));
});
});
答案 0 :(得分:1)
问题是从http调用返回的响应对象包含您想要的数据,但它本身并不是您想要的。
要访问请求内部的数据(即请求的主体),您需要调用.json()方法:
if (this.validation(obj)) {
this.httpService.loginPostToServer(obj).subscribe(
(response) => this.saveTokenToLocalstorage(response.json()), // .json() added here
(error) => console.log(error)
);
}
};