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

瘦欲@ 提交于 2019-12-03 04:18:20
Bartosz Dabrowski

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');
        }));
    });
});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!