在 Jasmine 测试中无法访问 Angular 服务函数

Angular service functions can't be accessed in Jasmine Tests

本文关键字:访问 Angular 服务 函数 Jasmine 测试      更新时间:2023-09-26

我对Jasmine Testing和Angular框架相当陌生。我目前有一个特殊的情况,我无法从我的 Jasmine 测试中引用我的服务功能。

我的 Angular 服务初始化的一部分:

var service = {
checkIfCurrentIsObject: checkIfCurrentIsObject,
removeFromCurrentObject: removeFromCurrentObject;
}
function checkIfCurrentIsObject() {
          return getCurrent().isObject();
       }
function removeFromCurrentIsObject() {
         checkIfCurrentIsObject();
          return specialFunction();
       }

现在在我的业力测试中:

describe('when current object is property', function() {
             it('verify the requote function is called', function() {
             spyOn(Service, 'checkIfCurrentIsObject').and.returnValue(true);
             spyOn(Service, 'removeFromCurrentIsObject').and.callThrough();
             spyOn(Service, 'specialFunction');
             expect(Service, 'specialFunction').toHaveBeenCalled();
                    });

现在我面临的问题是,我的 spyOn 不会接收我的 checkIfCurrentIsObject 函数,除非我在 removeFromCurrentIsObject 函数中将其指定为this.checkIfCurrentIsObject。这有什么特别的原因吗?

是的,应该是

 function removeFromCurrentIsObject() {
     this.checkIfCurrentIsObject();
     return this.specialFunction();
 }

监视他们。

这是

正在监视Service.checkIfCurrentIsObject方法。在 JavaScript 中,无法跟踪checkIfCurrentIsObject()本地函数调用。