【发布时间】:2020-03-14 07:13:35
【问题描述】:
我在 Angular 7 中有一个组件,它有服务作为构造函数参数。
@Component({
selector: 'cc-schedule-list',
templateUrl: './schedule-list.component.html',
styleUrls: ['./schedule-list.component.scss']
})
export class ScheduleListComponent implements OnInit {
constructor(public accountActivityService: AccountActivityService) {}
ngOnInit(): void {
}
}
基础服务
@Injectable({
providedIn: 'root'
})
export class BaseService {
public commonHeaders: CommonHeaderModel;
public legacyData: any;
constructor(
public httpClient: HttpClient,
public appService: AppService
) {
this.legacyData = this.appService.getDataFromLegacy();
this.commonHeaders = {
'sourceRequestID': 'KBB',
'uuid': this.legacyData.UUID,
};
}
getData(url: string, serviceHeaders: any, params?: any) {
const headers = {...this.commonHeaders, ...serviceHeaders};
return this.httpClient.get(url, {headers: headers, params: params});
}
}
AccountActivityService
@Injectable({
providedIn: 'root'
})
export class AccountActivityService {
constructor(public base: BaseService) {
}
/**
* getPendingPayments Function gets the all the pending payment transactions
*
* @returns All transactions on the account
*/
getPendingPayments(electronicCardIdentifier, payeeAccountIdentifier) {
return null; //return null at present
}
}
ScheduleListComponent.spec 文件
describe('ScheduleListComponent', () => {
let component: ScheduleListComponent;
let fixture: ComponentFixture<ScheduleListComponent>;
let injector: any;
let debugElement: DebugElement;
let accountActivityService: MockAccountActivityService;
/** Mock Account Activity Service ***/
class MockAccountActivityService extends AccountActivityService {
getPendingPayments() {
return null;
}
}
beforeEach( (() => {
TestBed.configureTestingModule({
declarations: [ ScheduleListComponent],
imports: [
...
],
providers: [ UserUtilService, { provide: AccountActivityService, useClass: MockAccountActivityService}],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
fixture = TestBed.createComponent(ScheduleListComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
accountActivityService = debugElement.injector.get(MockAccountActivityService);
}));
it('should create', () => {
expect(component).toBeDefined();
});
});
我总是收到这个错误 ***角度测试无法读取未定义或空引用的属性“UIID”。
可能是我的 ScheduleListComponent 没有将 MockAccountActivityService 作为构造函数参数。请在这里帮助我
【问题讨论】:
-
您是否尝试过设置断点并查看失败的地方?如果您对这些代码文件进行堆栈闪电战也会有所帮助,这样我们可以更轻松地提供帮助。
-
为什么在组件的测试中创建一个MockBaseService,因为组件对BaseService没有任何依赖?为什么不使用 jasmine 创建模拟对象?
-
MockBaseService 只是为了测试目的而创建的,因为我遇到了错误,所以我做到了。
-
那么测试的目的是什么?为什么你认为需要一个 mock base service 来测试一个不依赖 BaseService 的组件?
-
好的,我已经从规范文件中删除了 MockBaseService
标签: angular jasmine karma-jasmine