问题描述
我使用 John papa 角度样式指南,我的控制器看起来像:
I use John papa angular style guide my controller looks like:
遵循风格约翰爸爸风格控制器风格指南:
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");
});
});
结果:
测试失败:结果消息:预期未定义.在堆栈中
Test failed:Result Message: Expected undefined to be defined. at stack
所以我的问题是我们如何测试 vm.model 和其他变量?我没有在指南中找到合适的指南:controllers
So my question is how can we test vm.model and other variables from this? I have not found proper guide line in the guide lines: controllers
推荐答案
vm
通过 vm = this;
因此,所有属性都直接挂在对象上.
Therefore, all the properties are hanging directly off of the object.
function foo(){
var vm = this;
vm.name = 'Josh';
}
var myFoo = new foo();
myFoo.name; // 'Josh';
所以你需要做的就是改变你的期望以删除 vm
属性.
So all you need to do is change your expectations to remove the vm
property.
expect(testController).toBeDefined();
expect(testController.model).toBeDefined();
expect(testController.model.name).toEqual("controllerAs vm test");
为了证明这一点,这是您的确切示例以及相关的 Jasmine 测试.
In order to prove this, here is your exact example, and the associated Jasmine tests.
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>
这篇关于如何用茉莉花测试 John papa vm.model 单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!