如何在 Angualr Jasmine Karma 测试用例中模拟间谍并返回 Observable

问题描述 投票:0回答:1

如何在这种情况下监视可观察和模拟数据。 在我的 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个回答
0
投票

您正在测试

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

© www.soinside.com 2019 - 2024. All rights reserved.