【问题标题】:Angular2 test componentAngular2 测试组件
【发布时间】:2016-11-11 16:22:57
【问题描述】:

您好,我正在尝试在 Angular2 中测试我的组件,但在尝试模拟我的服务时遇到了问题。我目前正在关注有关测试的 Angular2 文档。

我正在调用我从 Angular 服务构建的后端 API,只要我有 JWT 令牌,它就可以正常工作。 但是在测试方面,我只想在我的组件测试中模拟服务。

服务

@Injectable()
export class ItemService {
    constructor(private _http: AuthHttp, private _store: Store<AppStore>) {}

        items(): Observable<any[]> {
            return this._http.get(ENDPOINT_ITEMS, {withCredentials: false})
                .map((response: Response) => response.json().data);
        }
}

组件

@Component({
 selector: 'items',
 template: require('./items.component.html'),
 providers: [ItemService]
})

export class ItemsComponent {
 items: Observable<Array<Object>>;

 constructor(private _service: ItemService) {}

  ngOnInit(): any {
    this.items = this._service.items();
  }
}

组件测试

beforeEach(() => {
TestBed.configureTestingModule({
    declarations: [ ItemsComponent ],
    providers:    [
        { provide: ItemService, useValue: itemsMock },
    ] 
});
fixture = TestBed.createComponent(ItemsComponent);
itemService = fixture.debugElement.injector.get(ItemService)

我希望我的模拟 ItemService 为我返回 useValue,itemsMock,以便我可以测试我的 html 标记是否具有正确的数据。 但看起来我的服务并没有被嘲笑对吧?

收到此错误:

错误:./ItemsComponent 类 ItemsComponent_Host 中的错误 - 内联模板:0:0 原因是:没有 AuthHttp 提供程序!在 karma.entry.js 中(第 17341 行)

【问题讨论】:

    标签: unit-testing angular angular2-services angular2-testing


    【解决方案1】:

    您的组件在其提供程序中有ItemService。这意味着每次创建组件的实例时,都会为组件创建一个新的 ItemService 实例。不会使用模块级别的服务。

    您的服务是无状态的,并且可能没有充分的理由处于组件级别。从提供者中删除它,并确保它在模块的提供者中。

    【讨论】:

    • 非常感谢!更进一步,它可以工作,是时候重构了! ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多