小编Sud*_*r V的帖子

单元测试spyOn在angular2中的可观察服务

我有一个服务(ChildService),它依赖于另一个服务(InteractWithServerService).以后的服务(InteractWithServerService)用于进行服务器调用并返回"any"类型的observable.为简单起见,我们假设它返回了observable.我正在尝试为ChildService编写单元测试.

ChildService

@Injectable()
export class ApplicationService {
    constructor(private  interactWithServerService:InteractWithServerService){;}

    public GetMeData():string {
        var output:string;       
        this.interactWithServerService.get("api/getSomeData").
           subscribe(response =>{console.log("server response:", response);
           output=response});        
         return output;
    }
}
Run Code Online (Sandbox Code Playgroud)

ServerInteractionService

@Injectable()
export class InteractWithServerService {        
    constructor(private http: Http) {
        ;
    }    
    get(url: string): Observable<any> {        
        return this.http.get(this.url);
    }       
}
Run Code Online (Sandbox Code Playgroud)

当我模拟依赖服务时,测试用例工作正常.即

class MockInteractWithServerService {
    get() {
        return Observable.of("some text");
    }           
}

describe('Service:ChildService', () => {
    let childService: ChildService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
             { provide: InteractWithServerService, useClass: MockInteractWithServerService },
                ChildService],
        });


    beforeEach(inject([ChildService], (actualService: ChildService) => …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript angular

12
推荐指数
1
解决办法
2万
查看次数

标签 统计

angular ×1

typescript ×1

unit-testing ×1