Angular2 在 ngOnInit 错误中测试带有 EventEmitter 订阅的模块

Angular2 testing a module with an EventEmitter subscription in ngOnInit error

我在为我创建的 Angular2 组件编写测试模块时遇到问题。有问题的组件在它的 ngOnInit 方法中订阅另一个服务的 EventEmitter。然后该组件订阅此 EventEmitter 并监听更改。这是有问题的组件:

import { Component } from "@angular/core";
import { Product } from "../../../classes/Product";
import { ProductService } from "../../../services/product.service";
import { ConfigObject } from "../../../ConfigObject";
import { productHelper } from "../../../helpers/productHelper";


@Component({
    selector: 'product-component',
    templateUrl: '/app/views/catalog/products/product-dashboard.html',
    moduleId: module.id
})

export class ProductComponent {
    globals = ConfigObject;
    products: Product[] = [];
    productsLoaded = false;

    productPayload = {
        order           : 'asc',
        order_by        : 'title',
        category_id     : 0,
        resize          : true,
        imgHeight       : 200,
        imgWidth        : 200,
        active          : 1,
        searchTerm      : '',
        manufacturer    : null
    };

    constructor(
        private _productService: ProductService
    ) {

    }

    getProducts(filters) {
        this.productsLoaded = false;

        this._productService.getProducts(filters)
            .subscribe(
                products => { this.products = productHelper.processImagesAndDownloads(products)},
                ()       => { },
                ()       => { this.productsLoaded = true }
        );
    }

    ngOnInit() {
        this._productService.emitter.subscribe(
            (products) => {
                this.products = productHelper.processImagesAndDownloads(products);
            },
            ()       => { },
            ()       => { }
        );

        this.getProducts({});
    }

}

如您所见,使用 ngOnInit 方法订阅了 _productService.emitter EventEmitter。

我曾尝试使用 spyOn 方法来模拟此事件发射器,但没有成功。我似乎无法正确测试此组件。任何人都可以看到这里的问题是什么:

import { ProductService } from "../../../../services/product.service";
import { TestBed, ComponentFixture, async } from "@angular/core/testing";
import { ProductComponent } from "../../../../components/catalog/products/ProductComponent";
import { HttpModule } from "@angular/http";
import { DebugElement, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";

let MockProductService = {
    emitter: () => {}
};

let comp:    ProductComponent;
let fixture: ComponentFixture<ProductComponent>;
let de:      DebugElement;
let el:      HTMLElement;

describe('Component: Product Component', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [
                ProductComponent
            ],
            providers: [
                {
                    provide: ProductService, useValue: MockProductService
                }
            ],
            imports: [
                HttpModule
            ],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        });
    });

    it('Should check that products are loaded in the template', async(() => {

        TestBed.compileComponents()
            .then(() => {

                fixture = TestBed.createComponent(ProductComponent);
                comp = fixture.componentInstance;

                spyOn(MockProductService, 'emitter').and.returnValue({
                    subscribe: () => {}
                });
                comp.ngOnInit();

                expect(MockProductService.emitter).toHaveBeenCalled();
        });
    }));

});

我收到的错误是:

Failed: Uncaught (in promise): TypeError: this._productService.emitter.subscribe is not a function

emitter 不会作为组件的方法被调用。它只能作为 属性

访问
this._productService.emitter

而且因为它永远不会作为方法被调用,所以你的间谍是无用的。

您可以将 emitter 的值分配给 Observable。这样,当组件订阅时,它实际上获得了一个值

import 'rxjs/add/observable/of';

MockProductService.emitter = Observable.of(products);

// don't call ngOnitInit. Use detectChanges instead
fixture.detectChanges();

// wait for observable subscription to resolve
fixture.whenStable().then(() => {
  // do other stuff
  expect(comp.products).toBe(whatever)
})

您还需要处理模拟中的 getProducts 方法。

顺便说一句,EventEmitter 并不是真的要用于服务。为此你应该使用 Subjects。它们几乎是一回事,但仍然建议不要以这种方式使用 EventEmitter。只是 google 如何使用 Subjects。我敢肯定那里有一堆 articles/post。