gpt4 book ai didi

angularjs - 如何使用 jasmine 测试 John papa vm.model 单元测试?

转载 作者:行者123 更新时间:2023-12-02 21:46:18 26 4
gpt4 key购买 nike

我使用 John papa Angular 风格指南我的 Controller 看起来像:

遵循风格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 = this;vm 等于实例本身

因此,所有属性都直接卡在对象上。

function foo(){
var vm = this;

vm.name = 'Josh';
}

var myFoo = new foo();
myFoo.name; // 'Josh';

因此,您需要做的就是改变您的期望以删除 vm 属性。

expect(testController).toBeDefined();  
expect(testController.model).toBeDefined();
expect(testController.model.name).toEqual("controllerAs vm test");

为了证明这一点,这是您的确切示例以及相关的 Jasmine 测试。

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>

关于angularjs - 如何使用 jasmine 测试 John papa vm.model 单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com