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

标签 angular testing jasmine eventemitter

我在为我创建的 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

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

您可以将 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 并不是真的要用于服务。为此,您应该使用 Subject。它们几乎是一回事,但仍然建议不要以这种方式使用 EventEmitter。只需谷歌一下如何使用 Subject。我敢肯定那里有很多文章/帖子。

关于Angular2 在 ngOnInit 错误中测试带有 EventEmitter 订阅的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41146611/

相关文章:

javascript - 如何在 Angular 2 项目中导入 js 包?

javascript - 如何将推特时间轴嵌入到 Angular4 应用程序

java - 如何在 Java 上使用单元测试来测试与类的私有(private)字段的交互?

python - 如何在python setup.py test中使用unittest2

javascript - 运行毯.js

css - 在一个 Angular 应用程序中动态切换两个 styles.css 文件

python - 即使使用 Auth Pre-Flight 的头,Python Falcon 的 CORS 失败

testing - 录制脚本 - "page not found"因为单一协议(protocol)?

angular - 测试在构造函数上使用 observable 的方法

javascript - 我可以让 Chrome 更具错误描述性吗?