2017-06-16 49 views
0

我有一個組件測試,其中我通過使用angularjs的$controllerProvider來模擬組件的控制器。注射工作正常,但即使在註冊期間,控制器上下文this也是undefined控制器未定義單元測試,即使在嘲笑之後

我的組件

import templateUrl from './pdf-export-modal.html.pug'; 
import './pdf-export-modal.less'; 

export default { 
    templateUrl, 
    bindings: { 
    onClose: '&', 
    }, 
    controller: 'PdfExportModalCtrl', 
}; 

和組件測試文件

import angular from 'angular'; 

describe('component: pdf-export-modal',() => { 
    let $rootScope; 
    let $compile; 
    let scope; 
    let el; 
    let html; 
    let ctrl; 

    beforeEach(angular.mock.module('mainModule', ($controllerProvider) => { 
    $controllerProvider.register('PdfExportModalCtrl',() => { 
     ctrl = this; 
     console.log(ctrl, this); // both are undefined here 
    }); 
    })); 

    beforeEach(inject((_$rootScope_, _$compile_) => { 
    $rootScope = _$rootScope_; 
    $compile = _$compile_; 
    scope = $rootScope.$new(); 
    html = "<pdf-export-modal on-close='onClose'/>"; 
    scope.onClose = jasmine.createSpy('onClose'); 
    el = $compile(html)(scope); 
    scope.$apply(); 
    })); 

    describe('selecting compact',() => { 
    // test 
    }); 
}); 

回答

0

的問題是與ES6自動綁定。對於PdfModalCtrl,使用來自測試類instead of creating a new onethis上下文的箭頭函數。刪除了箭頭功能並使用ES5語法使其工作。

beforeEach(angular.mock.module('mainModule', ($controllerProvider) => { 
    $controllerProvider.register('PdfExportModalCtrl', function() { 
    ctrl = this; 
    console.log(ctrl); //new context is created for the controller  
}); 
}));