如何用John papa做JohnPapavm.model单元测试?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (29)

代码如下:

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而不是testController

describe('Controller: testController', function () {
    // we work with "vm" instead of "testController" to have consistent verbiage
    // in test and controller
    var vm;

    beforeEach(module('app'));
    beforeEach(inject(function ($controller) {
        vm = $controller('testController', {}, {});
    }));

    it('should have vm.model defined and testController.vm.model is equal to controllerAs vm test', function () {

        // vm=this in controller
        expect(vm)
            .toBeDefined();

        // Testing primitives
        expect(vm.foo)
            .toBeDefined();
        expect(vm.foo)
            .toEqual('bar');

        // Testing objects
        expect(vm.model)
            .toBeDefined();
        expect(vm.model.name)
            .toEqual("Batman");

        // Testing a method
        expect(vm.greet())
            .toBeDefined();
        expect(vm.greet())
            .toEqual('Hello There');
    });
});

控制器代码

(function () {
    'use strict';

    angular
        .module('app')
        .controller('testController', testController);

    /* @ngInject */
    function testController() {
        var vm = this;

        // Primitives
        vm.foo = 'bar';

        // Objects
        vm.model = {
            name: 'Batman'
        };

        // Methods
        vm.greet = function () {
            return 'Hello There';
        };
    }
})();
用户回答回答于

代码如下:

function foo(){
  var vm = this;

  vm.name = 'Josh';
}

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

扫码关注云+社区

领取腾讯云代金券