使用Jasmine检查函数中的内部变量

问题描述 投票:0回答:1

我在AngularJS应用程序中使用Jasmine和Karma进行单元测试。我需要检查控制器功能中内部变量的值。

这是我的控制器。

(function() {
    'use strict';
    angular
        .module('testApp',[])
        .controller('testController', testController);

    function testController($http, $scope, $timeout) {
        var vm = this;
        vm.getTestValues = getTestValues;

        function getTestValues(){

            vm.serverError = undefined;
            vm.priceList = [];

            $http.get('https://example.com/api/getPrice').then(function(response) {

                vm.priceList = response.data;

                vm.value = vm.priceList[0].itemValue;

                vm.totalValue = vm.value * 10;              

            }).catch(function(e){
                vm.serverError = 'Server Error';
            });
        }
    }
})();

这是我的测试代码

describe('Test Controller', function() {
  beforeEach(module('testApp')); 

  var ctrl;

  beforeEach(inject(function($rootScope, $controller){

    scope = $rootScope.$new();
    ctrl = $controller('testController', { $scope: scope });
  }));


  describe('vm.value', function() {
    it('Should be ', function() {     

        ctrl.getTestValues();

        console.log(ctrl.priceList);


    });
  });  

});

console.log(ctrl.priceList);打印[]

我如何访问vm.priceListvm.valuevm.totalValue中的值?

angularjs jasmine karma-runner karma-jasmine
1个回答
0
投票

$http.get是一个异步电话。您将不得不使用$httpBackend对http服务进行单元测试。

您可以浏览以下链接以了解更多信息。

https://docs.angularjs.org/api/ngMock/service/$httpBackend

how to test $http call in angular js?

© www.soinside.com 2019 - 2024. All rights reserved.