使用MockHttpClientModule替换HttpClientModule学习心得

锦城 2020-11-07 20:56:01
使用 学习心得 mockhttpclientmodule 替换 httpclientmodule


前言

之前的项目测试采用的是使用Stub替换原有的组件进行测试,如今的问卷系统采用了新的思想,就是使用使用MockHttpClientModule替换HttpClientModule,前后台接口完全统一,更接近于真实请求,本文以总结学习心得为主,总结一下该方法的思路。

方法

首先看一下要测试的方法:

/**
* 通过试卷ID获取答卷
* 1. 如果存在尚未完成的答卷,则返回尚未完成的答卷
* 2. 如果不存在尚未完成的答卷,则新建一个答卷返回
* @param id 试卷ID
*/getByPaperId(id: number): Observable<AnswerSheet> {
return this.httpClient.get<AnswerSheet>(`${this.baseUrl}/${id}`);
}

测试方法:

beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MockApiModule
],
providers: [
MockHttpClient
]
});
service = TestBed.inject(AnswerSheetService);
});
it('测试模拟接口服务是否生效', () => {
expect(service).toBeTruthy();
let called = false;
service.getByPaperId(123).subscribe(data => {
expect(data.id).toEqual(123);
called = true;
});
getTestScheduler().flush();
expect(called).toBeTrue();
});

MockHttpClient

export class MockHttpClient {
constructor(private mockApiService: MockApiService) {
}
get<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
params?: HttpParams | {
[param: string]: string | string[];
};
}): Observable<T> {
return this.mockApiService.get<T>(url, options);
}

MockApiService

get方法

/**
* get方法 * @param url 请求地址
* @param options 选项
*/
get<T>(url: string, options = {} as {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
params?: HttpParams | {
[param: string]: string | string[];
};
}): Observable<T> {
return this.request<T>('get', url, {
observe: 'response',
responseType: 'json',
headers: options.headers,
params: options.params
});
}
}

request

/**
* 所有的GETPOSTDELETEPUTPATCH方法最终均调用request方法。 * 如果当前request不能够满足需求,则请移步angular官方提供的HttpClient * * 该方法先根据method进行匹配,接着根据URL进行正则表达式的匹配。 * 匹配成功后将参数传入接口并获取模拟接口的返回值 * * @param method 请求方法
* @param url 请求地址
* @param options 选项
*/
request<R>(method: string, url: string, options: {
body?: any;
headers?: HttpHeaders | {
[header: string]: string | string[];
};
reportProgress?: boolean;
observe: 'response';
params?: HttpParams | {
[param: string]: string | string[];
};
responseType?: 'json';
withCredentials?: boolean;
}): Observable<R> {
let result = null as R;
let foundCount = 0;
const urlRecord = this.routers[method] as Record<string, RequestCallback<any>>;
for (const key in urlRecord) {
if (urlRecord.hasOwnProperty(key)) {
const reg = new RegExp(key);
if (reg.test(url)) {
const callback = urlRecord[key] as RequestCallback<R>;
callback(url.match(reg), options.params, options.headers, (body) => {
result = body;
foundCount++;
if (foundCount > 1) {
throw Error('匹配到了多个URL信息,请检定注入服务的URL信息,URL信息中存在匹配冲突');
}
});
}
}
}
if (null === result) {
throw Error('未找到对应的模拟返回数据,请检查url、method是否正确,模拟注入服务是否生效');
}
return testingObservable(result);
}

registerMockApi

/**
* 注册模拟接口 * @param url 请求地址
* @param method 请求方法
* @param callback 回调
*/
registerMockApi<T>(method: RequestMethodType, url: string, callback: RequestCallback<T>): void {
if (undefined === this.routers[method] || null === this.routers[method]) {
this.routers[method] = {} as Record<string, RequestCallback<T>>;
}
if (isNotNullOrUndefined(this.routers[method][url])) {
throw Error(`在地址${url}已存在${method}的路由记录`);
}
this.routers[method][url] = callback;
}

AnswerSheetApi

registerGetByPaperId()

private baseUrl = '/answerSheet';
/**
* 注册GetByPaperId接口
* 注册完成后,当其它的服务尝试httpClient时
* 则会按此时注册的方法、URL地址进行匹配
* 匹配成功后则会调用在此声明的回调函数,同时将请求地址、请求参数、请求header信息传过来
* 我们最后根据接收的参数返回特定的模拟数据,该数据与后台的真实接口保持严格统一 */
registerGetByPaperId(): void {
this.mockHttpService.registerMockApi<AnswerSheet>(
`get`,
`^${this.baseUrl}/(d+)$`,
(urlMatches, httpParams, httpHeaders, callback) => {
const id = urlMatches[1];
callback({
id: +id
});
}
);
}

injectMockHttpService

/**
* MOCK服务。
*/mockHttpService: MockApiService;
/**
* 注入MOCK服务
** @param mockHttpService 模拟HTTP服务
*/
injectMockHttpService(mockHttpService: MockApiService): void {
this.mockHttpService = mockHttpService;
this.registerGetByPaperId();
}

MockApiService

constructor()

/**
* 注册模拟接口
* @param clazz 接口类型
*/
static registerMockApi(clazz: Type<Api>): void {
this.mockApiRegisters.push(clazz);
}
/**
* 循环调用从而完成所有的接口注册 */
constructor() {
MockApiService.mockApiRegisters.forEach(api => {
const instance = new api();
instance.injectMockHttpService(this);
});
}

// AnswerSheetApi
MockApiService.registerMockApi(AnswerSheetApi);

testingObservable

/**
* 返回供测试用的观察者
* 如果当前为测试过程中,则调用cold方法返回观察者将不出抛出异常。
* 否则使用of方法返回观察者
* @param data 返回的数据
* @param delayCount 延迟返回的时间间隔
*/
export function testingObservable<T>(data: T, delayCount = 1): Observable<T> {
try {
let interval = '';
for (let i = 0; i < delayCount; i++) {
interval += '---';
}
return cold(interval + '(x|)', {x: data});
} catch (e) {
if (e.message === 'No test scheduler initialized') {
return of(data).pipe(delay(delayCount * 500));
} else {
throw e;
}
}
}

MockApiModule


/**
* 模拟后台接口模块
* 由于MockHttpClient依赖于MockApiService
* 所以必须先声明MockApiService,然后再声明MockHttpClient
* 否则将产生依赖异常
* 每增加一个后台模拟接口,则需要对应添加到providers。
* 否则模拟接口将被angular的摇树优化摇掉,从而使得其注册方法失败
*/
@NgModule({
providers: [
MockApiService,
{provide: HttpClient, useClass: MockHttpClient},
AnswerSheetApi
]
})
export class MockApiModule {
}

总结

image.png

版权声明
本文为[锦城]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000037758347

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple