我有这项服务:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Session } from '../models/Session';
@Injectable()
export class SessionService {
sessionsURL = "http://localhost:8080/express/ux/sessions";
constructor(private http: HttpClient) { }
getSessions(arg1: string, arg2: string): Observable<any[]> {
return this.http.get<Session[]>(this.sessionsURL + this.buildArguments(arg1,arg2));
}
}
此方法在UserComponent
的{{1}}方法中被调用,如下所示:
onInit
这确实可以正常运行该应用程序。
但是,当我尝试模拟该方法时,在这样的sessionsReceived;
ngOnInit() {
(...)
this.sessionService.getSessions(this.modelInput.user, this.companyInput).subscribe(sessions => {
this.sessionsReceived = sessions;
});
(...)
}
文件中:
.spec.ts
该import { async, ComponentFixture, TestBed, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { UsersViewComponent } from './users-view.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MyDateRangePickerModule } from 'mydaterangepicker';
import { NgxEchartsModule, NgxEchartsService } from 'ngx-echarts';
import { Observable } from 'rxjs';
import { SessionService } from '../Services/session.service';
import { SortingService } from '../sorting.service';
import { testSet } from '../test/testSet';
import { Session } from '../models/Session';
describe('UsersViewComponent', () => {
let component: UsersViewComponent;
let service;
let fixture: ComponentFixture<UsersViewComponent>;
function fireEvent(id, event) {
const nativeElement = fixture.nativeElement;
const elem = nativeElement.querySelector('#' + id);
elem.dispatchEvent(new Event(event));
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, ReactiveFormsModule, MyDateRangePickerModule, NgxEchartsModule, HttpClientTestingModule],
declarations: [UsersViewComponent],
providers: [
NgxEchartsService,
SessionService,
SortingService
]
})
.compileComponents();
fixture = TestBed.createComponent(UsersViewComponent);
component = fixture.componentInstance;
service = TestBed.get(SessionService);
spyOn(service, 'getSessions').and.callFake(function () {
console.log("called");
return Observable.of(testSet);
});
component.ngOnInit();
fixture.detectChanges();
console.log("Variable" + component.sessionsReceived);
});
it('should create', () => {
fireEvent("worldMapChart", "chartInit");
fixture.whenStable().then(() => {
expect(component).toBeTruthy();
});
});
日志未打印,因此组件的called
变量保留为sessionsReceived
。
知道这可能是什么或我在做什么错吗?
谢谢!