如何用茉莉花测试这种角度方法

时间:2015-06-15 13:46:22

标签: angularjs jasmine

我的角度控制器中有以下方法。请注意,Upload.upload方法在apply方法中。

$scope.apply = function () {
    $scope.validationErrors.reset();

    if ($scope.firstName.trim() === '') {
        $scope.validationErrors.firstName = 'First name is required.';
    }

    if ($scope.validationErrors.isValid()){

        Upload.upload({
            url: '/apply',
            fields: {
                'first_name': $scope.firstName,
                'last_name': $scope.lastName
            },
            file: $scope.localFile,
            fileName: $scope.filename
        }).success(function(data){
            if (data === 'successfully saved application'){
                $location.path('/thanks/' + $scope.jobId);
            }else{
                $scope.errorMessage = 'Woops, something went wrong with your application. ' + data;
            }
        });
    }
};

我无法弄清楚如何测试方法的成功部分。这是我到目前为止,但它在scope.apply()行引发错误,说成功是未定义的。

describe('apply calls the uploader upload method', function () {
    var upload;
    var returnMessage = 'successfully saved application';
    var deferred;

    beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http, $q, Upload) {
        deferred = $q.defer();
        upload = Upload;
        httpBackend = $httpBackend;
        scope = $rootScope.$new();
        httpBackend.when('POST', '/apply').respond(returnMessage);
        $controller('ApplyController', {
            $scope: scope,
            $routeParams: { id: 1 },
            $http: $http,
            $q: $q,
            Upload: Upload,
            jobService: jobService
        });
        spyOn(upload, 'upload').and.returnValue(deferred);
    }));

    it('calls the Upload upload method', function () {
        scope.firstName = scope.lastName = scope.phoneNumber = scope.zipCode = scope.filename = 'test';
        scope.jobId = 1;
        scope.emailAddress = 'test@test.com';
        scope.apply();
        expect(upload.upload).toHaveBeenCalled();
    });
});

如何测试此方法的成功部分?感谢。

1 个答案:

答案 0 :(得分:0)

您必须执行$ httpBackend.flush()才能获得模拟的http响应。假设其他一切都是正确的,下面的测试应该通过。查看更多信息here

it('calls the Upload upload method', function () {
        scope.firstName = scope.lastName = scope.phoneNumber = scope.zipCode = scope.filename = 'test';
        scope.jobId = 1;
        scope.emailAddress = 'test@test.com';
        scope.apply();
        httpBackend.flush();
        expect(upload.upload).toHaveBeenCalled();
    });

除此之外: - 在每次测试之后,验证是否已通过expect api定义了所有请求,并且还没有需要刷新的未完成请求。

afterEach(function() {
     $httpBackend.verifyNoOutstandingExpectation();
     $httpBackend.verifyNoOutstandingRequest();
   });

编辑: 发现了另一个问题。设置间谍时,您应该返回deferred.promise而不是延迟。试试这个: -

spyOn(upload, 'upload').and.returnValue(deferred.promise);

如果这也不起作用,你可以为此分享一个吸食者吗?