pro*_*ock 32 jasmine angularjs angularjs-scope hottowel karma-runner
请参见此处:http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
正如标题所示,我正在按照本教程[ http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing]来设置单元测试,除了事实之外一切都很好我似乎无法访问vm变量作为我的$ scope.
dashboard.js
var controllerId = 'dashboard';
angular.module('app')
.controller(controllerId, ['common', 'datacontext', dashboard]);
function dashboard(common, datacontext) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.title = 'Dashboard';
Run Code Online (Sandbox Code Playgroud)
dashboard.Spec.js
describe("app module", function() {
beforeEach(module("app"));
describe("dashboard", function() {
var scope,
controller;
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller;
}));
it("should assign Dashboard as title", function() {
controller("dashboard", {
$scope: scope
});
expect(scope.title).toBe("Dashboard");
});
});
});
Run Code Online (Sandbox Code Playgroud)
我试过的:当我在控制器依赖项中直接命名'$ scope'并为其设置"title"属性时,它可以工作(测试通过).但是,我想保持模式不变.
我也尝试直接在依赖关系中传入$ scope并将控制器参数命名为"vm"...
Karmas失败的测试消息是:预计未定义为'仪表板'
感谢任何帮助!
pro*_*ock 58
啊,现在很明显......我可以通过引用在测试中创建的控制器来访问vm变量:
it("should assign Dashboard as title", function () {
var vm = controller("dashboard", { $scope: scope });
expect(vm.title).toBe("Dashboard");
});
Run Code Online (Sandbox Code Playgroud)
Kri*_*nov 25
你也可以这样做:
it("should assign Dashboard as title", function () {
var controller = controller("dashboard as vm", { $scope: scope });
expect(scope.vm.title).toBe("Dashboard");
});
Run Code Online (Sandbox Code Playgroud)