【问题标题】:Angular: unexpected request (ngMockE2E - $httpBackend)Angular:意外请求(ngMockE2E - $httpBackend)
【发布时间】:2015-08-27 11:17:02
【问题描述】:

我正在尝试使用 Jasmine 测试 Angular 指令。

HTML 看起来像这样:

<html>
    <head>
        <title></title>
        <script src='/jasmine/jasmine.js'></script>
        <script src='/jasmine/jasmine-html.js'></script>
        <script src='/jasmine/boot.js'></script>
        <script src='/angular/angular.js'></script>
        <script src='/angular/angular-mocks.js'></script>
        <script src='/components/test-directive.js'></script>
        <script src='/app.js'></script>
        <script>
            angular.module('myAppTests', ['myApp', 'ngMockE2E'])
            .run(function($httpBackend){
                $httpBackend.whenGET(/^\/views\//).passThrough();
            });
        </script>
        <script src='/components/test-directive.spec.js'></script>
    </head>
    <body></body>
</html>

测试指令(/components/test-directive.js)

angular.directive('testDirective', function(){
    return {
        templateUrl:'/views/test-directive.html'
    };
});

测试文件(/components/test-directive.spec.js)如下所示:

describe('test directive', function(){
    beforeEach(module('myAppTests'));

    var element, $scope;

    beforeEach(inject(function($compile, $rootScope){
        element = angular.element('<div data-test-directive=""></div>');
        $scope = $rootScope;
        $compile(element)($scope);
        $scope.$digest();
    }));

    it('generates the correct HTML', function(){
        expect(element.html()).toContain('test content');
    });

});

还有 /views/test-directive.html

<p>test content</p>

运行测试时出现以下错误:

'Unexpected request: GET /views/test-directive.html'

【问题讨论】:

    标签: javascript angularjs jasmine


    【解决方案1】:

    尝试将其添加到您的过滤器中:

    $httpBackend.whenGET(/\.html$/).passThrough();
    

    【讨论】:

    • 感谢您的回答。虽然没有运气。仍然抛出相同的错误
    【解决方案2】:

    当您在测试中使用任何 injectmodule 时,它会隐式加载 ngMock 的模块,其中包括一个不发送请求的模拟 $httpBackEnd。

    一种选择是重用原来的 $httpBackend。

    angular.module('myAppTests', ['myApp', 'ngMock'])
      .factory('$httpBackend', function() {
        // use the original $httpBackend instead of the fake backend
        return angular.injector(['ng']).get('$httpBackend');
      });
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2013-11-15
      • 2015-05-28
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多