【发布时间】:2019-11-06 17:56:32
【问题描述】:
我正在尝试对以下代码进行单元测试,我为单元测试编写了以下代码,如下所示,我尝试了很多工作方式,但我不断收到错误:
'无法读取属性'num' of undefined'
我不知道为什么没有正确设置范围。如果您对此有任何想法,可以给一些建议吗?
var angular = require('angular');
require('angular-mocks');
describe('test directive', function () {
let $rootScope;
let $compile;
let scope;
let newScope;
let element;
beforeEach(angular.mock.inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
describe('test directive', function () {
beforeEach(function () {
newScope = $rootScope.$new();
element = $compile('<test-directive></test-directive>')(newScope);
newScope.$digest();
scope = element.isolateScope();
});
fit('scope initialized', function () {
expect(scope.num).toEqual(1);
});
});
});
module.exports = module.directive('testDirective', ['$rootScope', '$scope', function($rootScope, $scope) {
return {
template: require('./test.html'),
restrict: 'E',
controller: [
'$scope',
function ($scope) {
$scope.num = 1
$scope.sum = function(a, b) {
return a + b;
}
}]
}
}]);
【问题讨论】:
-
如果指令中没有使用 $rootScope,为什么还要引用它?
-
其实我是用来播的,只是这里不包括而已。
-
你看到SO stackoverflow.com/q/21578762/1501613了吗?
-
我已经调查过了,但还是有问题。
标签: angularjs unit-testing scope angularjs-scope