如何使用Jasmine测试Angular Factory对象

How to test Angular Factory Objects using Jasmine

本文关键字:Factory 对象 Angular 测试 何使用 Jasmine      更新时间:2023-09-26

我试图解决的问题是使用Jasmine测试我的工厂的能力。

以下是我的应用程序和工厂的副本:

var app = angular.module('app', []);
app.factory('service', function ($http) {
    return {
        getCustomers: function (callback) {
            $http.get('/Home/Customers').success(callback);
        },
        getProfile: function (callback, viewModel) {
            $http.post('/Home/Profiles', JSON.stringify(viewModel), {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).success(callback);
        }
    };
});

::::

我也设置了jasmine,但在测试上面的"getCustomers"answers"getProfile"时遇到了问题。

以下是我目前的尝试:

  describe("getCustomers", function (service) {
      beforeEach(module('service'));
         describe('getCustomers', function () {
            it("should return a list of customers", inject(function(getCustomers){
              expect(getCustomers.results).toEqual(["david", "James", "Sam"]);
         }))
      })
  });

如果有人能提供一个如何在两个单独的测试中测试"getCustomers"answers"getProfile"的例子,这将非常有用。

致以亲切的问候。

您可以模拟Http GET请求并测试类似的服务

describe("getCustomers", function (service) {
    beforeEach(module('app'));
    var service, httpBackend;
    beforeEach(function () {
        angular.mock.inject(function ($injector) {
            httpBackend = $injector.get('$httpBackend');
            service = $injector.get('service');
        })
    });
    describe('getCustomers', function () {
        it("should return a list of customers", inject(function () {
            httpBackend.expectGET('/Home/Customers').respond(['david', 'James', 'Sam']);
            service.getCustomers(function (result) {
                expect(result).toEqual(["david", "James", "Sam"]);
            });
            httpBackend.flush();
        }))
    })
});

工作演示