Karma 单元测试在 phantomjs 中失败

Karma unit test fails in phantomjs

在测试中修复了很多错误后,现在Karma输出是这样的:

PhantomJS 1.9.8 (Windows 8 0.0.0) 控制器:MainCtrl 应该将列表附加到范围 FAILED
错误:意外请求:GET /api/marcas 在 ....

预计不会有更多请求

api/marcas 是我创建的端点。 MainCtrl 代码:

'use strict';

angular.module('app')
.controller('MainCtrl', function ($scope, $http, $log, socket, $location, $rootScope) {
    window.scope = $scope;
    window.rootscope = $rootScope
    $scope.awesomeThings = [];
    $scope.things = ["1", "2", "3"];



    $http.get('/api/things').success(function(awesomeThings) {
        $scope.awesomeThings = awesomeThings;
        socket.syncUpdates('thing', $scope.awesomeThings);
    });


    $scope.addThing = function() {   
        if($scope.newThing === '') {
            return;
        }


        $http.post('/api/things', { name: $scope.newThing });
        $scope.newThing = '';
    };

    $scope.deleteThing = function(thing) {
        $http.delete('/api/things/' + thing._id);
    };

    $scope.$on('$destroy', function () {
        socket.unsyncUpdates('thing');


    });



    $http.get('/api/marcas').success(function(marcas) {
        $scope.marcas = marcas;
        socket.syncUpdates('marcas', $scope.response);

        $scope.marcasArr = [];

        $scope.response.forEach(function(value) {
            $scope.marcas.push(value.name);
        });

        $scope.marcaSel = function() {
            for (i = 0; i < $scope.response.length; i++) {
                if ($scope.selectedMarca == $scope.response[i].name) {
                    $scope.modelos = $scope.response[i].modelos;
                };
            };      
        };



    });

直到你没有发布你的测试代码,我猜你的测试不包括以下代码:

beforeEach(inject(function () {
    httpBackend.expectGET('/api/marcas').respond(function(){
        return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
    });
}));

如果 karma-运行ner 试图执行你的测试代码,就会有对 $http-service 的 get-requests,$http.get('/api/marcas' ) 和 $http.get('/api/things')。如果这些后端调用之一不是预期的,业力不能 运行 测试代码成功。

如果你不想为每个都做特殊的事情,而只是 return 两个调用的默认值和成功代码,你可以这样写:

beforeEach(inject(function () {
    httpBackend.expectGET(/api/i).respond(function(){
        return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
    });
}));