4

The problem I'm trying to solve is the ability to test my factory using Jasmine.

Below is a copy of my app and factory:

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

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

I have also setup jasmine but I'm having trouble testing the above "getCustomers" and "getProfile".

Below is my current attempt:

  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"]);
         }))
      })
  });

This would be really helpful if someone could provide an example of how to test both "getCustomers" and "getProfile" in two separete tests.

Kind regards.

1 Answer 1

4

You can mock the Http GET request and test the service like this

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

Working Demo

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, Thank you for your response.
I still get this error: getCustomers encountered a declaration exception. ReferenceError: module is not defined in localhost:64550/Content/spec.js
@Mark Have a look at the working demo I created for you and you should be able to compare it with your solution.
Hi, I did that but still couldn't get it working. Seems to be something to do with how I've setup the spec runner.
I've now got this error with the spec runner: Failed to instantiate module myApp due to: [$injector:modulerr]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.