• [Angular Unit Testing] Testing Services with dependencies


    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);
          });
      });
    
    });
  • 相关阅读:
    本博客主题的相关配置(2021年)
    vscode侧边栏隐藏不需要的文件
    虎扑,豆瓣等用css屏蔽广告代码
    代替pandownload的百度网盘下载软件
    网络请求的超时原因
    OkHttp3系列(三)okhttp3-fast-spring-boot-starter
    OkHttp3系列(二)MockWebServer使用
    OkHttp3系列(一)初识OkHttp3
    为什么要使用短链接
    Google Guava之简化异常和错误的传播与检查
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6801901.html
Copyright © 2020-2023  润新知