参见这里例如:
http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
正如标题所示,我遵循本教程[http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing]设置单元测试,一切都很好,除了事实,我似乎不能访问vm变量作为我的$范围。
仪表板
- 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”属性。但是,我想保持这个模式。
我还尝试直接在依赖关系中传递$ scope,并将控制器参数命名为“vm”…
Karmas失败的测试消息是:预期未定义为“Dashboard”
欣赏任何帮助!
啊,显然现在…我可以通过引用在测试中创建的控制器访问vm变量:
- it("should assign Dashboard as title",function () {
- var vm = controller("dashboard",{ $scope: scope });
- expect(vm.title).toBe("Dashboard");
- });