Angular resource testing: $httpBackend.flush() cause Unexpected request

后端 未结 2 653
甜味超标
甜味超标 2021-02-06 05:25

I want to test angularjs resource.

\'use strict\';

/**
 * AddressService provides functionality to use address resource in easy way.
 *
 * This is an example us         


        
相关标签:
2条回答
  • 2021-02-06 05:36

    I have finally found solution:

    I tried to follow this: other post

    So I added $templateCache:

    'use strict';
    
    var $httpBackend;
    
    describe('Service: AddressService', function () {
    
        beforeEach(module('myApp'));
    
        beforeEach(inject(function ($injector, $templateChache) {
            $templateCache.put('views/home.html', '.<template-goes-here />');
            var url_get = 'api/v1/models/address/5';
    
            var response_get = {
                address_line_1: '8 Austin House Netly Road',
                address_line_2: 'Ilford IR2 7ND'
            };
    
            $httpBackend = $injector.get('$httpBackend');
    
            $httpBackend.whenGET(url_get).respond(response_get);
    
        }));
    
        describe('AddressService get test', function () {
            it('Tests get address', inject(function (AddressService) {
                var address = AddressService.get({ id: '5'});
                $httpBackend.flush();
                expect(address.address_line_1).toEqual('8 Austin House Netly Road');
                expect(address.address_line_2).toEqual('Ilford IR2 7ND');
            }));
        });
    });
    
    0 讨论(0)
  • 2021-02-06 05:58

    the error is caused by your test attempting to load the main page for your app. Since you have not told the test to expect this server call, an error is returned. See the documentation for $httpBackend for clarification on this point.

    Your $templateCache workaround is designed for unit testing directives not anything else. You were quite close with:

    $httpBackend.when('GET', /\.html$/).passThrough();
    

    Since you don't need to do anything with the actual template file it's a safe and simple work around to add this to your beforeEach() block.

    $httpBackend.whenGET(/\.html$/).respond('');
    

    This stops you getting the TypeError you had.

    TypeError: Object #<Object> has no method 'passThrough'
    

    I had the same issue in my unit tests after upgrading to a new version of Angular JS and using respond('') worked fine.

    0 讨论(0)
提交回复
热议问题