当使用AngularJS HotTowel中的vm“ControllerAs”语法时,从单元测试文件访问$scope

前端之家收集整理的这篇文章主要介绍了当使用AngularJS HotTowel中的vm“ControllerAs”语法时,从单元测试文件访问$scope前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见这里例如: http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/

正如标题所示,我遵循本教程[http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing]设置单元测试,一切都很好,除了事实,我似乎不能访问vm变量作为我的$范围。

仪表板

  1. var controllerId = 'dashboard';
  2. angular.module('app')
  3. .controller(controllerId,['common','datacontext',dashboard]);
  4.  
  5.  
  6. function dashboard(common,datacontext) {
  7. var getLogFn = common.logger.getLogFn;
  8. var log = getLogFn(controllerId);
  9.  
  10. var vm = this;
  11. vm.title = 'Dashboard';

dashboard.Spec.js

  1. describe("app module",function() {
  2. beforeEach(module("app"));
  3.  
  4. describe("dashboard",function() {
  5. var scope,controller;
  6.  
  7. beforeEach(inject(function($rootScope,$controller) {
  8. scope = $rootScope.$new();
  9. controller = $controller;
  10. }));
  11.  
  12. it("should assign Dashboard as title",function() {
  13. controller("dashboard",{
  14. $scope: scope
  15. });
  16. expect(scope.title).toBe("Dashboard");
  17. });
  18. });
  19. });

我试过的:它工作(测试通过),当我命名’$ scope’直接在控制器依赖和设置“title”属性。但是,我想保持这个模式。

我还尝试直接在依赖关系中传递$ scope,并将控制器参数命名为“vm”…

Karmas失败的测试消息是:预期未定义为“Dashboard”

欣赏任何帮助!

啊,显然现在…我可以通过引用在测试中创建的控制器访问vm变量:
  1. it("should assign Dashboard as title",function () {
  2. var vm = controller("dashboard",{ $scope: scope });
  3. expect(vm.title).toBe("Dashboard");
  4. });

猜你在找的Angularjs相关文章