【问题标题】:How to mock spyon and return an Observable in Angualr Jasmine Karma Test case如何在 Angular Jasmine Karma 测试用例中模拟 spyon 并返回一个 Observable
【发布时间】:2023-02-26 17:06:47
【问题描述】:

如何在这种情况下监视可观察和模拟数据。 在我的 Angular 14 应用程序中,我正在使用 jasmine 和 karma 编写单元测试。 以下是服务(UserService),我想模拟可观察的并返回模拟数据。 它有一个 getUserPrefer 方法,该方法调用 HTTP get 并返回 UserModel 类型的 ApiResp。

UserService.ts
export class UserService {

  constructor(private _http: HttpClient, private cService: CService) {
   }
      getUserPrefer(str: string): Observable<ApiResp<UserModel>> {
        return this._http.get<ApiResp<UserModel>>(this._cService.aConfig.customer + `v1/getuser/${str}`);
       }
}

CService.ts
export class CService {
  public get config(): IApp {
    return this._config;
  }

  public get aConfig(): IApp {
    return this._config;
  }
}

IConfig.ts
export interface IApp {
  customer: string;
}

UserService.spec.ts

import { HttpClientModule } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} 
       from '@angular/common/http/testing';

import { UserService } from './UserService';
import { Observable} from 'rxjs';


describe('UserService', () => {
  let service: UserService;
  let userModel: UserModel;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule]
    });
    service = TestBed.inject(UserService);
  });



  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should get UserPreference', () => {
   
   service.getUserPrefer('newuserjohn');
     spyOn(service, 'getUserPrefer')
         .and.returnValue(userModel);  
  });

});

ApiResp.ts
export interface ApiResp<T = {}> {
    status: number;
    timestamp: string;
    error?: string;
    message?: string;
    payload?: T;
}

export class UserModel {
  email!: string;
  id!: string;

  constructor(res: UserModel) {
    this.email = res.email;
  }
}

【问题讨论】:

    标签: angular jasmine spyon


    【解决方案1】:

    您正在测试UserService,所以我不希望您模拟在该服务中实现的函数——您应该只模拟依赖项。因此你实际上想要模拟HttpClient,为此你应该使用HttpClientTestingModule

    let httpTestingController: HttpTestingController;
    ...
    imports: [
      ...
      HttpClientTestingModule,
      // don't import the real HttpModule
      ...
    ]
    ...
    httpTestingController = TestBed.inject(HttpTestingController);
    
    ...
    it('should get UserPreference', waitForAsync(() => {
       service.getUserPrefer('newuserjohn').subscribe((response_ => {
         expect(reponse).toEqual(mockUser); 
       }, fail);
    
       const url = 'your expected URL';
       const req = httpTestingController.expectOne(url);
    
       // mockUser will be returned from the mock http call, hence the check in the expect above
       req.flush(mockUser); 
    
       expect(req.request.method).toBe('GET');
    }));
    
    

    https://angular.io/api/common/http/testing/HttpTestingController

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多