【问题标题】:Angular - Mock subscribe in component's methodAngular - 模拟订阅组件的方法
【发布时间】:2019-01-10 08:25:34
【问题描述】:

我在组件中有一个方法调用这样的服务方法:

method() {
    // Code before ...

    this.productService.getProducts().subscribe((data: any[]) => {
        const products = [];

        // Many calculations on data ...

        this.products = products;
    }); 
}

对于我的单元测试,我需要在调用 productService.getProducts() 时模拟返回的数据。

我做了很多研究,但没有找到任何解决方案。我该怎么做?

【问题讨论】:

    标签: angular unit-testing jasmine observable karma-runner


    【解决方案1】:

    你应该看看Component with async service。我们可以让 spy 用this.productService.getProducts() 方法的测试数据返回一个同步的 Observable。

    这是一个使用 angular v11+ 的工作示例:

    example.component.ts:

    import { Component } from '@angular/core';
    import { ProductService } from './product.service';
    
    @Component({})
    export class ExampleComponent {
      products: any[];
      constructor(private productService: ProductService) {}
      method() {
        this.productService.getProducts().subscribe((data: any[]) => {
          this.products = data;
        });
      }
    }
    

    product.service.ts:

    import { Injectable } from '@angular/core';
    import { of } from 'rxjs';
    
    @Injectable()
    export class ProductService {
      getProducts() {
        return of(['Your real implementation']);
      }
    }
    

    example.component.spec.ts:

    import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
    import { of } from 'rxjs';
    import { ExampleComponent } from './example.component';
    import { ProductService } from './product.service';
    
    fdescribe('54124518', () => {
      let productServiceStub: jasmine.SpyObj<ProductService>;
      let fixture: ComponentFixture<ExampleComponent>;
      let component: ExampleComponent;
      beforeEach(
        waitForAsync(() => {
          productServiceStub = jasmine.createSpyObj('ProductService', [
            'getProducts',
          ]);
    
          TestBed.configureTestingModule({
            declarations: [ExampleComponent],
            providers: [{ provide: ProductService, useValue: productServiceStub }],
          })
            .compileComponents()
            .then(() => {
              fixture = TestBed.createComponent(ExampleComponent);
              component = fixture.componentInstance;
            });
        })
      );
    
      it('should pass', () => {
        productServiceStub.getProducts.and.returnValue(of(['fake implementation']));
        component.method();
        expect(component.products).toEqual(['fake implementation']);
        expect(productServiceStub.getProducts).toHaveBeenCalled();
      });
    });
    

    单元测试结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 2017-10-03
      • 1970-01-01
      • 2021-12-14
      • 2019-01-25
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多