[英]Angular Unit Test: How to mock properties in a method?
Here is the service that I am trying to test: 这是我要测试的服务:
@Injectable()
export class BomRevisiosnsService {
constructor(
private baseService: BaseService,
private appConstants: AppConstants,
private dmConstants: DMConstants
) { }
public getRevisionsData(): any {
var itemId = this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
let url = this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";
let headers = {
"Content-Type": "application/json",
UserExecutionContext: JSON.stringify(this.appConstants.userPreferences.UserBasicDetails),
}
if (itemId != null || itemId != undefined) {
return this.baseService.getData(url, headers).map(response => {
return response;
});
}
}
}
spec file spec文件
describe('bom-revisions.service ',()=>{
let bomRevisiosnsService:BomRevisiosnsService;
let baseService: BaseService;
let appConstants: AppConstants;
let dmConstants: DMConstants;
beforeEach(()=>{
baseService=new BaseService(null,null);
appConstants=null;
dmConstants=null;
bomRevisiosnsService=new BomRevisiosnsService(baseService,appConstants,dmConstants);
});
it('getRevisionsData() call base service getData()',()=>{
let spy = spyOn(baseService, 'getData').and.returnValue(Observable.of())
bomRevisiosnsService.getRevisionsData();
expect(baseService.getData).toHaveBeenCalled();
});
})
Error: TypeError: Cannot read property 'userPreferences' of null
错误:TypeError:无法读取null的属性“userPreferences”
I believe I need to provide some mock value for this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
我相信我需要为
this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
提供一些模拟值this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
and this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";
和
this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";
Yes, indeed, you need to provide a valid value for appConstants
and dmConstants
because the call to bomRevisiosnsService.getRevisionsData()
uses that information internally. 是的,实际上,您需要为
appConstants
和dmConstants
提供有效值,因为对bomRevisiosnsService.getRevisionsData()
的调用会在内部使用该信息。
So, instead of assigning null
to appConstants
and dmConstants
, you could create an objects with some valid data, like this: 因此,您可以创建一个包含一些有效数据的对象,而不是为
appConstants
和dmConstants
指定null
,如下所示:
appConstants = {
userPreferences: {
modelData: {
basicDetails: {
itemId: 3 // some other valid value here is fine
}
},
UserBasicDetails: {
// some valid values here, maybe
}
}
};
dmConstants = {
URLs: {
GETBOMREVISIONS: 'revisions' // or just some valid value according to the use case
}
};
And the same goes to baseService
. 同样适用于
baseService
。
In general, you need to create valid stub, mock, etc for all object, services, etc that are used internally by the service you're testing. 通常,您需要为您正在测试的服务在内部使用的所有对象,服务等创建有效的存根,模拟等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.