javascript - 如何在我的情况下测试 http 请求?

标签 javascript angularjs unit-testing

我有这样的服务。

这只是简单地发出一个http get 请求。

angular.module('myApp').service('TESTService', ['$http',
    function($http) {
        var request = function(url) {
            return $http({
                method: 'GET',
                url: url
            });
        };
        return {
            get: function(url) {
                return request(url);
            }            
        };
    }
]);

在我的 Controller 中,我调用了该服务

 TESTService.get('/api/product' + id).success(
            function(result) {
                console.log(result)
            }
        );

我需要为其编写单元测试

describe('test here', function () {
var testCtrl, scope, httpBackend, testService;

// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_,  _TESTService_) {
    scope = _$rootScope_.$new();
    httpBackend = _$httpBackend_;
    testService = _TESTService_;

    testCtrl = _$controller_('testCtrl', {
        $scope: scope
    });



     it('should return http data', function() {
        var productData = {
           data: [
                {
                  obj: {
                    id:'123'
                  }
                }           
            ]
        }

        httpBackend.expectGET('/api/product/' + id).respond(productData);

        TESTService.get('/api/product/' + id).
            then(function(data) {
                var result = data;
            })

        httpBackend.flush();
        expect(result).toEqual(productData)
    });
 }));

运行测试后,我得到了

Error: Unexpected request: GET /api/product/undefined

如何编写测试以确保其通过?有任何想法吗?非常感谢!

最佳答案

您的变量“id”似乎未定义。如果你投入

var id = 123; 

此行之前:

httpBackend.expectGET('/api/product/' + id).respond(productData);

它将调用/api/product/123。

所以也许您一开始就在寻找这个:

 httpBackend.expectGET('/api/product/' + productData.data[0].obj.id).respond(productData);

 TESTService.get('/api/product/' + productData.data[0].obj.id).

等等...希望有帮助!

关于javascript - 如何在我的情况下测试 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28421804/

相关文章:

angularjs - 如何为 AngularStrap datetimepicker 显示 'invalid date' 验证消息

javascript - 错误: Auto count the adding of textbox which is not supposed to be

javascript - 当它是包含对象的数组时如何在 JSDoc 中记录变量?

javascript - 当存在多个比较运算符时,为什么 onkeypress 不使用 IE 调用 javascript 函数

javascript - 服务功能未触发

multithreading - 如何优化Grails构建和测试执行速度?

javascript - 使用具有淡入和淡出效果的 jQuery 更改悬停列表的背景主体图像 + 缩放

angularjs - 服务对象更新时 $watch 不更新

ruby-on-rails - PGError : ERROR: source database "template1" is being accessed by other users

angular - 使用 stub 测试 Angular 服务