如何你测试茉莉花的IIFE内定义的angularjs模块? [英] How to you test an angularjs module defined inside an IIFE with jasmine?

查看:106
本文介绍了如何你测试茉莉花的IIFE内定义的angularjs模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么上测试茉莉这个模块?
问题是,这是非常困难的测试 $控制器因为函数隐藏在闭包内,这是非常困难的测试。

how do I test this module on jasmine ? The problem is that it's very difficult to test the $controller because the function is hidden inside a closure, it’s very difficult to test them.

在换句话说,给定以下模块定义,写一个单元测试用于MainCtrl似乎是不可能的。

In other words, given the module definition below, writing a unit test for MainCtrl seems impossible.

(function () {

    'use strict';

    angular.module('app', []);

    function MainCtrl() {
      var mc = this;
      mc.obj = {
        val : 50  
      };
    }

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

} () );

和典型茉莉测试

describe('app', function(){

  beforeEach(module('app'));

  it('should create an objet with val 50', inject(function(_$controller_) {
    var scope = {},
        ctrl = _$controller_('MainCtrl', {$scope:scope});

    expect(scope.obj.val).toBe(50); // returns Expected undefined to be 50.
  }));

});

在角注入 _ $ _控制器茉莉花测试功能里面的服务,控制器的实例创建返回一个未定义$范围。

When angular inject the _$controller_ service inside the jasmine test function, The instance of the controller created returns with an undefined $scope.

所以你怎么能测试它?

我在计算器上一个解决这个问题的搜索,没有给我,我一直在寻找让我实现了我自己的一个答案。

My search on StackOverflow for a solution to this problem, didn't give me the answer I was looking for so I implemented one of my own.

推荐答案

可以茉莉花简单地通过这样的测试:

It can be tested with jasmine simply by doing this :

describe('app', function () {

    var $controller;

    beforeEach(function () {

        module('app');

        inject(function (_$controller_) {

            $controller = _$controller_('MainCtrl');

        });
    });

    //-- spec - test controller

    describe('Controller : MainCtrl', function () {

        it('should create an object with val 50', function () {

            expect($controller.obj.val).toBe(50);

        });
    });

});

这里有一个的jsfiddle

希望它帮助!

这篇关于如何你测试茉莉花的IIFE内定义的angularjs模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆