Angular2 测试组件

Angular2 test component

您好,我正在尝试在 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 为我 return useValue,itemsMock,这样我就可以测试我的 html 标签是否具有正确的数据。 但是我的服务好像没有被嘲笑吧?

出现此错误:

Error: Error in ./ItemsComponent class ItemsComponent_Host - inline template:0:0 caused by: No provider for AuthHttp! in karma.entry.js (line 17341)

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

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