javascript - 使用 Jasmine 进行 http post 方法的单元测试用例

标签 javascript angularjs unit-testing jasmine

我尝试为 Angular 服务中的 post 方法编写一个单元测试用例。我收到 $http 未定义错误。下面是我的代码。任何人都可以告诉我我错过了什么。 我正在使用单独的文件添加模块。 服务代码

 sample.factory('AddProductTypeService', function () {
    return {
        exciteText: function (msg) {
            return msg + '!!!'
        },
        saveProductType: function (productType) {
            var result = $http({
                url: "/Home/AddProductTypes",
                method: "POST",
                data: { productType: productType }
            }).then(function (res) {
                return res;
            });
            return result;
        }
    };

});

Jasmine

describe("AddProductTypeService UnitTests", function () {

    var $rootScope, $scope, $factory, $httpBackend, basicService,createController, authRequestHandler;

    beforeEach(function () {
        module('sampleApp');

        inject(function ($injector) {
            basicService = $injector.get('AddProductTypeService');
            // Set up the mock http service responses
            $httpBackend = $injector.get('$httpBackend');


        });
    });
    // check to see if it does what it's supposed to do.
    it('should make text exciting', function () {
        var result = basicService.exciteText('bar');
        expect(result).toEqual('bar!!!');
    });

    it('should invoke service with right paramaeters', function () {
        $httpBackend.expectPOST('Home/AddProductTypes', {
            "productType": "testUser"          
        }).respond({});

        basicService.saveProductType('productType');
        $httpBackend.flush();
    });



});

错误:

引用错误:$http 未定义

提前致谢

最佳答案

您必须将 $http 服务注入(inject)您的服务

 sample.factory('AddProductTypeService', ['$http' ,function ($http) {
    /* ... */
 }]);

https://docs.angularjs.org/guide/di

关于javascript - 使用 Jasmine 进行 http post 方法的单元测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284535/

相关文章:

python - Unitest 用于处理异常的函数

java - 测试时模拟@Service 连接到数据库

javascript - 滚动父 DIV 时修复元素

javascript - Jquery 图像 slider 在 Macintosh 上不起作用

javascript - Google Analytics 计算我所有子域的访问次数,但将我的子域列为引荐

javascript - 如何使用最小/最大高度和高度将响应式 CSS 高度应用于元素?

css - 单元格中的下拉菜单被隐藏,无法正确显示

angularjs - 将选项卡 View 重新定位到 nativescript Angular 的底部

javascript - AngularJS 通过 $http.post 将更新的数据发送到 php 页面

unit-testing - FakeItEasy - 如何验证嵌套参数值 C#