使用 vm“ControllerAs"时从单元测试文件访问 $scope来自 AngularJS HotTowel 的语法 [英] accessing $scope from unit test file when using the vm "ControllerAs" syntax from AngularJS HotTowel
问题描述
参见此处的示例:http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
正如标题所示,我正在学习本教程 [http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing] 设置单元测试,一切都很好,除了我似乎无法访问虚拟机变量作为我的 $scope.
As the title suggests, I'm following along on this tutorial [http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing] to setup unit testing and all is fine EXCEPT for the fact I can't seem to access the vm variable as my $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';
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");
});
});
});
我尝试过的:当我直接在控制器依赖项中命名$scope"并将title"属性设置为它时,它可以工作(测试通过).但是,我想保持原样.
What I've tried: it works (the test passes) when I name '$scope' directly in the controllers dependencies and set the "title" property to it. However, I'd like to keep the pattern as is.
我也试过在依赖项中直接传入 $scope 并将控制器参数命名为vm"...
I've also tried passing in $scope directly in dependencies and naming the controller parameter as "vm"...
Karmas 失败测试消息是:预期未定义为仪表板"
Karmas failing test message is: Expected undefined to be 'Dashboard'
感谢任何帮助!
推荐答案
啊,现在很明显...我可以通过引用测试中创建的控制器来访问 vm 变量:
Ah, obvious now...I can access the vm variable through making a reference to the controller that's created in the test:
it("should assign Dashboard as title", function () {
var vm = controller("dashboard", { $scope: scope });
expect(vm.title).toBe("Dashboard");
});
这篇关于使用 vm“ControllerAs"时从单元测试文件访问 $scope来自 AngularJS HotTowel 的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!