javascript - 使用 Jasmine 和 Karma 进行 AngularJS 测试

标签 javascript angularjs jasmine karma-jasmine

我尝试测试一个 Angular Controller ,但他返回了一个 promise ,我无法真正解决它......我的代码有什么问题?

Angular Controller :

kpi.AboutController = function ($scope, Version) {

    function loadVersion() {
        //$scope.version = Version.getVersion();
        $scope.version = '1.1.0';
    }

    loadVersion();
};

和 Jasmine 测试:

describe('dashboard: AboutController', function() {
beforeEach(module('dashboard'));
var $controller;
beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
}));
it('testing the version number', function() {
    var $scope = {};
    var controller = $controller('AboutController', { $scope: $scope });
    var version = 0;
    console.log($scope.version);
    expect($scope.version).toContain("1.");
});
});

这是有效的,但是当我将行 $scope.version = '1.1.0'; 更改为 $scope.version = Version.getVersion();我收到一个 promise ,但无法检查它......我尝试通过 $scope.version.then(...) 使用“then()”函数解决它,但没有工作...做什么?

编辑:

发生以下错误:

Expected e({ $promise: Object({ $$state: Object({ status: 0 }) }), $resolved: false }) to contain '1.'.
    at Object.<anonymous>

和服务:

kpi.VersionFactory = function ($resource, appConfig) {
var Version = $resource(thePath, {}, {

    "getVersion": {
        method: "GET",
        url: thePath,
        isArray: false
    }

});

return Version;
};

最佳答案

您需要将回调传递到您的测试用例中。

kpi.AboutKPIController = function ($scope, Version) {

    $scope.loadVersion= function () {
      Version.getVersion().then(function(res){
                   $scope.version = res.data;
            })
    }

     $scope.loadVersion();
};
describe('dashboard: AboutKPIController', function() {
  beforeEach(module('dashboard'));
  var $controller;
  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter                names when matching
    $controller = _$controller_;
 }));
 it('testing the version number', function(done) {
    var $scope = {};
    var controller = $controller('AboutKPIController', { $scope: $scope });
    var version = 0;
    console.log($scope.version);
    $scope.loadVersion().then(function(res)){
             //can test here
             expect($scope.version).toContain("1.");
            done();
      });   
  });

});

关于javascript - 使用 Jasmine 和 Karma 进行 AngularJS 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31293104/

相关文章:

javascript - Cordova 插件未定义

javascript - 如何为两个对应模式之间的共享字符编写正则表达式?

javascript 与 jQuery 自定义/全局变量范围

javascript - $watchCollection 未被触发

angularjs - Angular JS-Jasmine 如何对 $location.path().search() 进行单元测试?

javascript - Flowplayer 在 Google Chrome 中加载但无法播放视频,但可以在其他浏览器中运行

javascript - 具有日期格式的 angularjs ng-options

angularjs - 在 uiRouter 中从子状态更改父 Controller 属性

javascript - 测试 Angular 组件时的 Jasmine spyOn 服务

json - 如何在 Angular 2 karma Jasmine 测试中从 JSON 文件加载模拟数据?