如何在我的情况下单元测试一个函数

时间:2015-08-13 19:16:21

标签: javascript angularjs unit-testing

我正在尝试为子控制器创建单元测试 在我的子控制器中,我在父

中调用了一个函数

子控制器

apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

defaultConfig {
    minSdkVersion 10
    targetSdkVersion 20
    versionCode 1
    versionName "1.0"
}
allprojects {
    repositories {
        mavenCentral()
        jcenter()
        mavenLocal()
        maven {
            url "${project.rootDir}/creativesdk-repo/release"
        }
    }
}

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }

}

dependencies {
    compile 'com.adobe.creativesdk.foundation:auth:0.3.94'
    compile 'com.adobe.creativesdk.image:4.0.0'
}

父控制器

$scope.clickMe = function(){
    $scope.parentMethod();
})

单元测试

$scope.parentMethod = function(item){
    //do something with parent
})

我正在

var childCtrl;

 beforeEach(module('myApp'));
    beforeEach(inject(function (_$controller_, _$rootScope_) {
        scope        = _$rootScope_.$new();
        childCtrl = _$controller_('childCtrl', {
            $scope: scope
        });
    }));

    describe('test parent', function() {
        it('should call parent', function() {
            $scope.clickMe();
            $httpBackend.flush();
        });
    });
});

我不知道如何解决这个问题。任何人都可以帮我吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

为了测试子控制器,你应该在范围内模拟方法

    scope        = _$rootScope_.$new();
    scope.parentMethod = function noop(){};
    childCtrl = _$controller_('childCtrl', {
        $scope: scope
    });

对于测试,应该用间谍替换noop。语法将取决于您使用Jasmine或Sinon的引擎。通过这种测试方式,可以验证是否已调用parentMethod