Testing $resource services in AngularJS

前端 未结 2 633
一整个雨季
一整个雨季 2020-12-22 22:41

I am trying to begin writing unit tests for my angular application and hit a stopping block pretty quick as I am unsure of how exactly to mock my service in a testable way.<

2条回答
  •  被撕碎了的回忆
    2020-12-22 23:43

    You can mock the requests made by ngResource like this:

    describe('User', function () {
        var mockUserResource, $httpBackend;
        beforeEach(angular.mock.module('myApp'));
    
        beforeEach(function () {
            angular.mock.inject(function ($injector) {
                $httpBackend = $injector.get('$httpBackend');
                mockUserResource = $injector.get('User');
            })
        });
    
        describe('getUser', function () {
            it('should call getUser with username', inject(function (User) {
                $httpBackend.expectGET('/api/index.php/users/test')
                    .respond([{
                    username: 'test'
                }]);
    
                var result = mockUserResource.getUser('test');
    
                $httpBackend.flush();
    
                expect(result[0].username).toEqual('test');
            }));
    
        });
    });
    

    Demo

提交回复
热议问题