Angular 单元测试:如何模拟方法中的属性?

Angular Unit Test: How to mock properties in a method?

这是我要测试的服务:

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

})

Error: TypeError: Cannot read property 'userPreferences' of null

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

是的,的确,您需要为 appConstantsdmConstants 提供有效值,因为对 bomRevisiosnsService.getRevisionsData() 的调用在内部使用该信息。

因此,与其将 null 分配给 appConstantsdmConstants,不如创建一个包含一些有效数据的对象,如下所示:

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

baseService也是如此。

一般来说,您需要为您正在测试的服务在内部使用的所有对象、服务等创建有效的存根、模拟等。