javascript - AngularJS Jasmine 测试 - 元素隔离范围未定义

标签 javascript angularjs unit-testing jasmine

我正在尝试测试超时,但我在元素的范围方面遇到了问题。我是编写 JS 测试的新手。

it('shouldhavetimerdefineatstart') 测试中,我的变量记录为未定义。这是为什么?

我认为isolateScope()会拉入指令的范围?

我的测试如下所示:

https://plnkr.co/edit/IMrPd9g6HFSkgHizFF9p?p=preview

describe( 'Testing timeout', function(){
  var scope, $timeout, element;

  beforeEach(inject( function ($rootScope, $compile, _$timeout_, $injector ){
            scope = $rootScope.$new();
            $timeout = _$timeout_;

            scope.onWarning = function(){
                scope.warned = true;
            };

            element = '<div timeout on-warning="onWarning" on-timeout="onTimeout"></div>';
            element = $compile(element)(scope);

            scope.$apply();
            scope.$digest();

  }));

  it( 'should have timer defined at start', function(){
    console.log( element.isolateScope() , scope )
    expect( element.isolateScope().timeoutService.timer ).not.toBeFalsy;
  });

  it( 'should have run warning function', function(){
    $timeout.flush( 5000 );
    expect( scope.warned ).toBe( true );
  });

});

我的指令如下所示:

app.directive( 'timeout', function( timeoutService ){
  return {
    restrict: "A",
    scope: {
                onWarning: "&", // what function to fire when showing a warning
            },
            link: function( scope, elem, attr ){
                scope.timeoutService = timeoutService;
                if( !scope.onWarning ){ 
                    throw new Error( "Must provide on-warning for timeout directive." );
                }
                //console.log( scope.onWarning, scope.onTimeout );
                // register timeouts and warnings with the service
                timeoutService.onWarning = scope.onWarning; 
            }
  }
}); 

app.service( 'timeoutService', function( $timeout ){
  var _this = this;
  var timer = null;
  var time = 5000;

  this.startTimer = function(){
    timer = $timeout( function(){
      if( _this.onWarning ){
        _this.onWarning()();
      }
    }, time)
  }

  this.startTimer();

})

也许我测试不正确?

最佳答案

您需要调用

beforeEach(module('plunker'));

在“测试超时”描述 block 中。您只是在另一个描述 block 中调用它

关于javascript - AngularJS Jasmine 测试 - 元素隔离范围未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37997387/

相关文章:

angularjs - Lumen With Angularjs 时的文件夹结构?

html - ionic 应用程序视频无法在移动设备上播放

javascript - Node JS 异步模块初始化模式

javascript - 使用数组方法的单词过滤器

javascript - :hover to tap twice for Mobile 上的下拉菜单

javascript - AngularJS 模板中的三元运算符

c# - 如何在 .NET Core 中使用 xUnit 测试 Xamarin ViewModel?

visual-studio-2008 - 在VS2008中,有什么方法可以将单元测试与集成测试分开吗?

java - 如何为scala play框架项目编写Java TestNG测试类?

javascript - Testcafe 抛出错误 invalid arg type