由于某种原因,我注入(inject)的范围没有被填充,实际上这可能有点明显,console.log
语句显示 Controller 直到测试之后才真正被执行已运行,但我不确定为什么或如何修复它。 更新:,我转储了Insert
,它似乎是一个空对象,这可能不是正确的事情......
define([
'angular-mocks',
'controllers/insert'],
function( mocks ) {
'use strict';
describe('Controller: Insert', function () {
// load the controller's module
beforeEach(module('pasteyApp'));
var Insert,scope,location,pastes;
// Initialize the controller and a mock scope
beforeEach(inject(function ( $injector, $controller, $rootScope ) {
pastes = $injector.get('pastes');
location = $injector.get('$location');
scope = $rootScope.$new();
scope.code = 'package Foo::Bar;',
Insert = $controller('Insert', {
$scope: scope,
$location: location,
pastes: pastes,
});
}));
it('has code', function () {
expect( scope.code ).toBe('package Foo::Bar;');
scope.$apply();
});
it('updates location', function () {
scope.view();
expect( location.path() ).not.toBe('');
expect( location.path() ).toBe('...');
expect( pastes ).toBe( {} );
});
});
});
Controller /插入件
define([
'crypto.MD5',
'angular',
'services',
], function() {
'use strict';
return ['$scope', '$location', 'pastes', function ( $scope, $location, pastes ) {
$scope.view = function( ) {
if ( $scope.code ) {
// boo hex, really want urlsafe base64
var digest = Crypto.MD5( $scope.code ).toString();
console.log( digest );
pastes[digest] = $scope.code;
}
$location.path( digest );
};
}];
});
Controller
define([
'app',
'services',
], function ( app ) {
'use strict';
return app
.controller('Insert', ['$scope','$injector', function( $scope, $injector ) {
require(['controllers/insert'], function( insert ) {
$injector.invoke( insert, this, { '$scope': $scope });
})
}])
.controller('Render', ['$scope','$injector', function( $scope, $injector ) {
require(['controllers/render'], function( render ) {
$injector.invoke( render, this, { '$scope': $scope });
});
}])
;
});
实际错误
Chrome 31.0.1650 (Linux) Controller: Insert updates location FAILED
TypeError: Object #<Scope> has no method 'view'
at null.<anonymous> (/home/xenoterracide/dev/Pastey/test/spec/controllers/insert.js:33:10)
最佳答案
我想我理解你的问题。由于 require()
是异步的,而您的 Jasmine 测试不是异步的,因此在您的规范运行时,“require/insert”函数尚未执行。您需要在 Jasmine 中找到一种方法,在执行 it()
block 之前等待 require 完成。
这就是为什么 Controller 是一个对象,但它上面还不存在任何东西。显然,您正在正确注册所有内容(否则 $controller()
会抛出异常),但没有等待 require.js 完成其工作足够长的时间。
看起来像this question能够很好地掌握您需要做什么。
关于javascript - 为什么我的 Angular 测试 $scope 上没有定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20327972/