我使用约翰·帕帕角度指导我的控制器看起来像:
遵循风格John papa style controller style guide:
function testController() { var vm = this; vm.model = { name: "controllerAs vm test" }; }
我的测试代码如下:
describe('Controller: testController',function () { beforeEach(module('myApp')); var testController; beforeEach(inject(function ($controller) { scope = {}; testController = $controller('testController',{ }); })); it('should have vm.model defined and testController.vm.model is equal to controllerAs vm test',function () { expect(testController.vm).toBeDefined(); expect(testController.vm.model).toBeDefined(); expect(testController.vm.model.name).toEqual("controllerAs vm test"); }); });
结果:
测试失败:
结果消息:预期未定义。
在堆栈
所以我的问题是我们如何从这个测试vm.model和其他变量?在指导线中没有找到正确的引导线:controllers
vm等于实例本身通过vm = this;
原文链接:https://www.f2er.com/angularjs/144199.html因此,所有的属性都直接挂在对象上。
function foo(){ var vm = this; vm.name = 'Josh'; } var myFoo = new foo(); myFoo.name; // 'Josh';
expect(testController).toBeDefined(); expect(testController.model).toBeDefined(); expect(testController.model.name).toEqual("controllerAs vm test");
为了证明这一点,以下是您的具体例子,以及相关的茉莉花测试。
function testController() { var vm = this; vm.model = { name: "controllerAs vm test" }; } angular.module('myApp',[]) .controller('testController',testController); describe('Controller: testController',function() { beforeEach(module('myApp')); var testController; beforeEach(inject(function($controller) { scope = {}; testController = $controller('testController',{}); })); it('should have model defined and testController.model.name is equal to controllerAs vm test',function() { expect(testController).toBeDefined(); expect(testController.model).toBeDefined(); expect(testController.model.name).toEqual("controllerAs vm test"); }); it('should not have a property called vm',function() { expect(testController.vm).toBeUndefined(); }); });
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine-html.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/boot.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.4/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.4/angular-mocks.js"></script>