我是角度测试的新手,正在尝试使用Angular实施模拟服务的基本测试。调用personalsettingmock.getPersonalSettings时出现“无法读取未定义的订阅”app.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PersonalSettingsComponent } from './personal-settings.component';
import { PersonalSettingsService } from './personal-settings.service';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { NotifyService } from 'src/app/_services/notify.service';
import { LoaderEmitterService } from 'src/app/_services/loader-emitter.service';
import { of } from 'rxjs/internal/observable/of';
fdescribe('PersonalSettingsComponent', () => {
let component: PersonalSettingsComponent;
let fixture: ComponentFixture<PersonalSettingsComponent>;
let personalSettingsServiceMock;
let notifyServiceMock;
let loaderEmitterServiceMock;
let data = {
email: 'asd', firstName: 'sff', lastName: 'sdf', phoneMobile: '+12355'
};
beforeEach(async(() => {
personalSettingsServiceMock = jasmine.createSpyObj(['getPersonalSettings']);
notifyServiceMock = jasmine.createSpyObj(['notifyUser']);
loaderEmitterServiceMock = jasmine.createSpyObj('LoaderEmitterSerivce', ['emitChange']);
TestBed.configureTestingModule({
declarations: [PersonalSettingsComponent],
imports: [
],
providers: [
{
provide: NotifyService,
useValue: notifyServiceMock
},
{
provide: LoaderEmitterService,
useValue: loaderEmitterServiceMock
}
],
schemas: [
NO_ERRORS_SCHEMA
]
});
TestBed.overrideProvider(PersonalSettingsService,{useValue: personalSettingsServiceMock});
TestBed.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PersonalSettingsComponent);
component = fixture.componentInstance;
personalSettingsServiceMock.getPersonalSettings.and.returnValue(of(data));
fixture.detectChanges();
});
it('should get user data from userService', () => {
expect(component).toBeTruthy();
expect(component.personalData).toBe(data);
fixture.detectChanges();
})
});
app.component.ts下面是我需要在组件中测试的方法
getUserData () {
this._loaderEmitter.emitChange(APP_CONSTANTS.SHOW_LOADING);
this.personalSettingsService.getPersonalSettings().subscribe( (responseData:PERSONAL_DATA) => {
this._loaderEmitter.emitChange(APP_CONSTANTS.HIDE_LOADING);
this.personalData = responseData;
this.setSettingsData();
this.personalData = _.omit(this.personalData, 'email');
this.setChangeDetection();
});
}
提前感谢。
因为它表示getPersonalSettings
“实际”实现使用您预订的Observable
,所以在测试中您必须模拟Observable
import { of } from 'rxjs';
personalSettingsServiceMock = jasmine.createSpyObj('PersonalSettingsService', {
getPersonalSettings: of({})
});
然后您还需要以这种方式将其添加到提供程序中:
{
provide: PersonalSettingsService,
useValue: personalSettingsServiceMock
}