角单元测试:如何在方法中模拟属性?

时间:2019-06-19 06:50:17

标签: javascript angular unit-testing jasmine angular-unit-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;
            });
        }
    }
}

规格文件

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();
});

})
  

错误:TypeError:无法读取null属性'userPreferences'

我认为我需要为this.appConstants.userPreferences.modelData['basicDetails']['itemId'];提供一些模拟值 和this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";

1 个答案:

答案 0 :(得分:0)

是的,实际上,您需要为c(t(outer(LETTERS[1:3], LETTERS[1:3], paste0))) #[1] "AA" "AB" "AC" "BA" "BB" "BC" "CA" "CB" "CC" appConstants提供有效值,因为对dmConstants的调用在内部使用了该信息。

因此,您可以创建带有一些有效数据的对象,而不是将bomRevisiosnsService.getRevisionsData()分配给nullappConstants,例如:

dmConstants

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 } }; 也是如此。

通常,您需要为要测试的服务在内部使用的所有对象,服务等创建有效的存根,模拟等。