以下是Angular7
Http
服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, retryWhen, retry } from 'rxjs/operators';
import { AddCustomer as Transaction} from '../../module/model/add-Customer.model';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})};
@Injectable({
providedIn: 'root'
})
export class CustomerService {
constructor(private http: HttpClient) { }
public addCustomer(newTransaction: Transaction): Observable<Transaction>
{
console.log(newTransaction);
return this.http.post<Transaction>('', newTransaction, httpOptions)
}
但不确定如何针对该服务编写测试。
答案 0 :(得分:0)
您可以使用
TestBed.configureTestingModule({
providers: [ MyService ]
});
const myService = TestBed.get(MyService);
针对myService运行测试。
如果您的服务具有依赖性,则还需要将它们包括在providers数组中。
答案 1 :(得分:0)
如Angular's documentation中所述,测试服务的最简单方法就是像其他任何类实例一样创建服务的实例。 (服务是轻量级类,但不是组件。)
describe('MasterService without Angular testing support', () => {
const client= new HttpClient(null);
spyOn(client, 'get').and.returnValue(Observable.of(response));
let service: CustomerService = new CustomerService(client);
您也可以按照Tzannetos Philippakos的建议使用Angular的测试实用程序。必须测试组件,这也可以省去一些设置工作。
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [CustomerService ]
});