[Angular Unit Testing] Testing Services with dependencies
Angular with Testing unit Services Dependencies
2023-09-14 09:00:51 时间
import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { StockInventoryService } from './stock-inventory.service'; TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ); function createResponse(body) { return Observable.of( new Response(new ResponseOptions({ body: JSON.stringify(body) })) ); } class MockHttp { get() { return createResponse([]); } } const cartItems = [{ product_id: 1, quantity: 10 }, { product_id: 2, quantity: 5 }]; const productItems = [{ id: 1, price: 10, name: 'Test' }, { id: 2, price: 100, name: 'Another Test' }]; describe('StockInventoryService', () => { let service: StockInventoryService; let http: Http; beforeEach(() => { const bed = TestBed.configureTestingModule({ providers: [ StockInventoryService, { provide: Http, useClass: MockHttp } ] }); http = bed.get(Http); service = bed.get(StockInventoryService); }); it('should get cart items', () => { // [...cartItems]: do a copy spyOn(http, 'get').and.returnValue(createResponse([...cartItems])); service.getCartItems() .subscribe((result) => { expect(result.length).toBe(2); expect(result).toEqual(cartItems); }); }); it('should get product items', () => { spyOn(http, 'get').and.returnValue(createResponse([...productItems])); service.getProducts() .subscribe((result) => { expect(result.length).toBe(2); expect(result).toEqual(productItems); }); }); });
相关文章
- [Angular RxJS] Single data observable pattern (combineLatest with startWith)
- [Angular] Write Compound Components with Angular’s ContentChild
- [Angular] Configure an Angular App at Compile Time with the Angular CLI
- [Angular2 Form] Group Inputs in Angular 2 Forms with ngModelGroup
- [Angular 2] Create template with Params
- [Unit Testing] Angular Test component with required
- [Angular-Scaled web] 1. Architecture and file structure
- [Angular 8 Unit testing] Testing a smart component with service injection -- 1
- [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
- [Angular] Make a chatbot with DialogFlow
- [Angular2 Animation] Control Undefined Angular 2 States with void State
- [Angular 2] Nesting Elements in Angular 2 Components with ng-content (AKA Angular 2 Transclusion)
- [Angular-Scaled web] 3. Basic State with ui-router
- Angular 应用里 server.ts 文件的 APP_BASE_HREF token 的用法?
- Angular [(ngModel)]的ng-dirty设置时机
- where and when is Angular scope initialized
- Angular里的structural directive的一个例子