2

我试图解释我的问题的简单版本。
1)我正在为控制器(myController)方法(减法)编写单元测试。
2) 使用 httpbackend 模拟 http 我想在减法中向 http 的成功函数返回 200 的响应,以降低其在任何虚拟 DELETE url 的成功函数中的值(在测试环境之外总是成功的)。
3)但我认为 expect(scope.testvalue) 仅为 5。任何帮助表示赞赏。

'use strict';
describe('MyController UNIT TEST specs ', function () {    
var scope, http, location, ctrl, httpBackend;
beforeEach(module('myApp', 'ui.router')); 

beforeEach(inject(function ($rootScope, $http, $controller, $httpBackend) {
    scope = $rootScope.$new();
    http = $http;
    httpBackend = $httpBackend;
    ctrl = $controller('myController', { $scope: scope, $http: http});
    httpBackend.when('DELETE', 'url').respond(200, 'fsdf');
}));

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

it('test 1 : Subtract 1 from a value enter code here` using subtract method in myController', function () {
    httpBackend.when('DELETE', 'url').respond(200);
    var testvalue = 5;
    scope.subtract(testvalue);
    expect(testvalue).toBe(4);
});
});
angular.module("myApp").controller("myController", function ($scope, $http) {    
    $scope.subtract = function (testValue) {    
        $http({
            method: 'DELETE',
            url: 'url'
        }).then(function (data) { //success    
            //irrespective of data subtract 1 here     
            testValue - 1 = 4;    
        }, function (errResult) { //fail
            console.log(errResult);
        });
    }
})

我看到的错误是(预期的) 错误:预期的错误为真。

4

1 回答 1

3

在使用 angular-mock 进行单元测试时,您必须httpBackend.flush()手动调用以开始模拟 http 请求/响应,然后才能获得如下结果:

it('test 1 : Subtract 1 from a value enter code here` using subtract method in myController', function () {
    httpBackend.when('DELETE', 'url').respond(200);
    var testObj = { testValue: 5 };
    scope.subtract(testObj);
    httpBackend.flush();
    expect(testObj.testValue).toBe(4);
});

并且您的 http 回调不会修改scope.testvalue,如果您希望testvalueinscope更改回调应该是这样的:

$scope.subtract = function (testObj) {
    $http({
        method: 'DELETE',
        url: 'url'
    }).then(function (data) { //success
        //irrespective of data subtract 1 here
        testObj.testValue = testObj.testValue - 1;
    }, function (errResult) { //fail
        console.log(errResult);
    });
};

有关完整的工作示例,请参见:http ://plnkr.co/edit/kFt5vV8zCtZpfJvduujc?p=preview

于 2014-07-15T11:57:47.937 回答