此测试现在正在运行!
我想在 Angular 2 中测试 HTTP 请求,但它不起作用。 这是错误消息:
ERROR in .../loginservice.service.spec.ts (45,11): ';' expected.
ERROR in .../loginservice.service.spec.ts (45,12): ')' expected.
这是代码: 这是一个帖子请求,并且工作正常。
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class LoginService {
constructor(private http: Http) { }
postLoginDetails(loginDetails): Observable<Comment[]> {
const endpoint = 'http://localhost:8080/api/login';
const bodyString = loginDetails;
const headers = new Headers({ 'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});
return this.http.post(endpoint, bodyString, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'server error'));
}
}
这是对其的测试: 这是对post请求的测试。我用不同的文章来写它,也许这就是它不起作用的原因。
import { TestBed, inject } from '@angular/core/testing';
import {
HttpModule,
Http,
XHRBackend,
ResponseOptions,
Response,
Headers
} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { LoginService } from './loginservice.service';
describe('LoginService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
LoginService,
{ provide: XHRBackend, useClass: MockBackend },
]
});
});
describe('postLoginDetails()', () => {
it('should return an Observable<Comment[]> with ok status',
inject([LoginService, XHRBackend], (LoginService, MockBackend) => {
const mockResponse = {
status: 'ok',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
}
const loginDetails = {
email: '[email protected]',
password: '1234'
};
MockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponse)
})));
});
LoginService.postLoginDetails(loginDetails).subscribe((mockResponse) => {
expect(mockResponse.status).toEqual('ok');
});
}));
});
});
关闭mockBackend.connections时存在不匹配
}
describe('postLoginDetails()', () => {
it('should return an Observable<Comment[]>', inject([LoginService, XHRBackend], (loginService, mockBackend) => {
const mockResponse = {
status: 'ok',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
};
mockBackend.connections.subscribe((connection) => {
const loginDetails = {
email: '[email protected]',
password: '1234'
};
loginService.postLoginDetails(loginDetails).subscribe((userInfo) => {
expect(userInfo.length).toBe(2);
expect(userInfo.status).toEqual('ok');
});
}));
});
});
更新:-修复了一些语法错误。
好问题。 是的,这绝对是假阳性测试...