激动人心的 Angular HttpClient的源码解析(2)

describe('HttpClient', () => { let client: HttpClient = null !; let backend: HttpClientTestingBackend = null !; beforeEach(() => { backend = new HttpClientTestingBackend(); client = new HttpClient(backend); }); afterEach(() => { backend.verify(); }); // 请求验证 describe('makes a basic request', () => { it('for JSON data', (done: DoneFn) => { client.get('/test').subscribe(res => { expect((res as any)['data']).toEqual('hello world'); done(); }); backend.expectOne('/test').flush({'data': 'hello world'}); }); it('for an arraybuffer', (done: DoneFn) => { const body = new ArrayBuffer(4); // 还支持 {responseType: 'text'}、{responseType: 'blob'} client.get('/test', {responseType: 'arraybuffer'}).subscribe(res => { expect(res).toBe(body); done(); }); backend.expectOne('/test').flush(body); }); it('that returns a response', (done: DoneFn) => { const body = {'data': 'hello world'}; client.get('/test', {observe: 'response'}).subscribe(res => { expect(res instanceof HttpResponse).toBe(true); expect(res.body).toBe(body); done(); }); backend.expectOne('/test').flush(body); }); }); });

发送 POST 请求

describe('makes a POST request', () => { it('with text data', (done: DoneFn) => { client.post('/test', 'text body', {observe: 'response', responseType: 'text'}) .subscribe(res => { expect(res.ok).toBeTruthy(); expect(res.status).toBe(200); done(); }); backend.expectOne('/test').flush('hello world'); }); it('with json data', (done: DoneFn) => { const body = {data: 'json body'}; client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe(res => { expect(res.ok).toBeTruthy(); expect(res.status).toBe(200); done(); }); const testReq = backend.expectOne('/test'); expect(testReq.request.body).toBe(body); testReq.flush('hello world'); }); });

发送 JSONP 请求

describe('makes a JSONP request', () => { it('with properly set method and callback', (done: DoneFn) => { client.jsonp('/test', 'myCallback').subscribe(() => done()); backend.expectOne({method: 'JSONP', url: '/test?myCallback=JSONP_CALLBACK'}) .flush('hello world'); }); });

参考资源

A Taste From The New Angular HTTP Client

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfyxj.html