【问题标题】:how to write tests for service in angular如何以角度编写服务测试
【发布时间】:2019-09-12 12:18:26
【问题描述】:

下面是Angular7Http服务

    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)
    }

但不确定如何针对该服务编写测试。

【问题讨论】:

    标签: angular jasmine karma-jasmine angular7


    【解决方案1】:

    你可以使用

    TestBed.configureTestingModule({
        providers: [ MyService ]
    });
    
    const myService = TestBed.get(MyService);
    

    针对 myService 运行测试。

    如果您的服务有依赖项,您还需要将它们包含在 providers 数组中。

    【讨论】:

      【解决方案2】:

      如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 ]
      });
      

      【讨论】:

        猜你喜欢
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 2019-04-19
        • 2020-11-03
        相关资源
        最近更新 更多