gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:39:03 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com