javascript - 如何在 Angular 7 中测试服务
问题描述
我想测试从我的服务收到的数据。我阅读了角度文档并遵循了 observable 示例,但是当我订阅 observable 时我没有收到任何数据。Console.log() 在订阅中不起作用。
该服务工作正常,并在真实环境中获取正确的数据。
我尝试使用 async 和 doneFn 但他们都没有工作,他们都超时了。
服务文件
export class BackService {
URL = '********'; // I removed url for security.
constructor(private httpClient: HttpClient) { }
getAllForms(): Observable<Array<object>> {
return this.httpClient.get<Array<object>>(`${this.URL}/allForms`);
}
getFormById(formId): Observable<Array<object>> {
return this.httpClient.get<Array<object>>(`${this.URL}/form/${formId}`);
}
}
测试服务文件
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { BackService } from './back.service';
describe('BackService', () => {
let httpMock: HttpTestingController;
let backService: BackService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [BackService]
});
backService = TestBed.get(BackService);
httpMock = TestBed.get(HttpTestingController);
});
it('should be created', () => {
expect(backService).toBeTruthy();
});
describe('Methods', () => {
describe('All Forms', () => {
it('should use GET method', () => {
backService.getAllForms().subscribe();
const req = httpMock.expectOne(`${backService.URL}/allForms`);
expect(req.request.method).toBe('GET');
});
it('should use the right url', () => {
backService.getAllForms().subscribe();
const req = httpMock.expectOne(`${backService.URL}/allForms`);
expect(req.request.url).toBe(`${backService.URL}/allForms`);
});
it('should return the right data', () => {
const mockData = [{'_id': 435345345, '_type': 'window'}]
backService.getAllForms().subscribe(data => {
expect(data).toEqual(mockData);
});
});
});
});
解决方案
前 2 个测试看起来没问题,对于第三个测试来接收您可以测试的数据,您必须通过使用您希望 httpClient 返回的必要对象调用其 flush() 方法来触发该“httpMock”。
这应该适用于第三次测试:
it('should return the right data', () => {
const mockData = [{'_id': 435345345, '_type': 'window'}]
backService.getAllForms().subscribe(data => {
expect(data).toEqual(mockData);
});
const req = httpMock.expectOne(`${backService.URL}/allForms`);
req.flush(mockData);
});
推荐阅读
- android - Dagger 应用程序组件未生成
- html - 使用内联样式的简单 flexbox 网格
- python - 如何使用appium查找哪个应用程序在前台
- android - 在后台加载图像并显示加载页面
- css - 在个人站点的根目录下为 GitHub Pages 准备 Jekyll(baseurl 不是不必要的吗?)
- .net - 隐藏扩展时如何避免 AssemblyName.exe.config 混淆?
- php - htaccess 无法将文章 ID 重定向到使用 php slug 函数生成的文章 slug
- firebase - Firebase Stream 功能无法正常工作
- php - 具有多个条件的 laravel 查询更新
- powerbi - Microsoft Power BI:折线图过去 13 周的数据 3 年