首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jasmine测试在组件中使用的角2服务

如何使用Jasmine测试在组件中使用的角2服务
EN

Stack Overflow用户
提问于 2017-04-11 22:32:09
回答 1查看 1.9K关注 0票数 1

我正在努力学习如何使用Jas明和角2和异步设置一个单元测试。我有一个调用服务的组件。但我好像碰到了路障。我有如下服务:item.service.ts

代码语言:javascript
复制
import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { Item } from "./item";
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class ItemService {
    private baseUrl = 'api/items/';  // web api URL 
    constructor(private http: Http) { }   

    // calls the [GET] /api/items/GetLatest/{n} Web API method to retrieve the latest items. 
    getLatest(num?: number) {
        let url = this.baseUrl + 'GetLatest/';
        if (num != null) { url += num; }
        return this.http.get(url)
            .map(response => response.json())
            .catch(this.handleError);
    }
}

我在组件(item-list.component.ts)中调用服务,如下所示:

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { Item } from './item';
import { ItemService } from './item.service';
import { GridModule } from '@progress/kendo-angular-grid';
import { GroupDescriptor, process } from '@progress/kendo-data-query';
import { SortDescriptor, orderBy } from '@progress/kendo-data-query';
import { GridDataResult } from '@progress/kendo-angular-grid';
import '@telerik/kendo-theme-default/dist/all.css';
@Component({
    selector: 'itemlist',       
    templateUrl: 'someItems.component.html',       

})

export class ItemListComponent implements OnInit {
    selectedItem: Item;
    items: Item[];
    errorMessage: string;
     groups: GroupDescriptor[];
     sort: SortDescriptor[] = [];
     gridView: GridDataResult;
    constructor(private itemService: ItemService) { }

    ngOnInit() {
        this.getLatest();
    }

    getLatest() {
        this.itemService.getLatest(5)
            .subscribe(latestItems => {
                console.log(latestItems);
                this.items = latestItems;
                this.gridView = {
                    data: orderBy(this.items, this.sort),
                    total: this.items.length
                };
            }, error => {
                console.log('error');
                this.errorMessage = <any>error;
            });
    }   

} 

这是我的item.component.spec.ts文件

代码语言:javascript
复制
import { async, inject, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ItemListComponent } from '../App/item-list.component';
import { ItemService } from '../App/item.service';
import { GridModule } from '@progress/kendo-angular-grid';
import { HttpModule, Http } from "@angular/http";
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/of';

class MockMyService {       
    public items: Array<any>;
    public getLatest(num?: number) {
        this.items = [{ Id: 1, Title: "test1", Description: "test12" }]
        return Observable.of(this.items);

    }
}

describe('Component:ItemList', () => {
    let fixture: ComponentFixture<ItemListComponent>;
    let itemService: MockMyService;

    describe('Async', () => {
        beforeEach(async(() => { 
            TestBed.configureTestingModule({
                declarations: [
                    ItemListComponent
                ],
                providers: [
                    //ItemService
                    { provide: ItemService, useClass: MockMyService }
                ],
                imports: [
                    GridModule,HttpModule
                ],
                schemas: [CUSTOM_ELEMENTS_SCHEMA]
            });

            fixture = TestBed.createComponent(ItemListComponent);
            itemService = fixture.debugElement.injector.get(ItemService);   

             spyOn(itemService, 'getLatest')
               .and.returnValue({ subscribe: () => { itemService.items} });                     

            fixture.detectChanges();               

        }));

        afterEach(() => {
            fixture = undefined;//teardown
        });                             

        it('should get items', () => {
             itemService.getLatest();
             expect(fixture.debugElement.componentInstance.items.length).toEqual(1);
        });    

    });
});

但是测试抛出错误如下-Chrome57.0.2987(Windows70.0.0)组件:ItemList异步应该获得项失败的TypeError:无法读取未定义的属性“长度”,如果有人能帮助我,我将非常感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-12 00:07:43

伙计,看看你的逻辑

代码语言:javascript
复制
class MockMyService {       
  public items: Array<any>;
  public getLatest(num?: number) {
    this.items = [{ Id: 1, Title: "test1", Description: "test12" }]
    return Observable.of(this.items);
  }
}

spyOn(itemService, 'getLatest')
  .and.returnValue({ subscribe: () => { itemService.items} }); 

在您的间谍(它覆盖真正的方法)中,您将返回itemService.items,在调用getLatest之前它甚至不会被初始化。这就是为什么它是没有定义的。

如果你已经在嘲弄这些数据,那就别管间谍了。如果你把它拿出来,它就能用了。如果希望更改每个测试的数据,则向其传递一个实际值,而不是使用未初始化的itemService.items

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43357269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档