【发布时间】: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;
}
}
【问题讨论】: