samedi 19 avril 2014

Testing a simple service with $httpBackend


Vote count:

0




I have a simple service that I want to test. I'm using $httpBackend to mock requests. I'm having problems getting the mocked data back after the ajax call. I know its asynchronous and I need to maybe use a promise. But the problem is I can't find a way to do it. what I think I should do is to use a .then() but Im not sure.



'use strict';

angular.module('adminApp').service("categoryService", function ($http) {

this.getAllCategories = function () {
var dataToSend = [];
console.log("GOING TO CALL GET");
$http.get("./category/categories").success(function(data, status, headers){
console.log("IN SUCCESS", data);
// i need to do something here to return the data to my test
dataToSend = data;
}).error(function(data, status, headers, config){
console.log("ERROR: ", data,status,headers,config);
dataToSend = "error";
});

return dataToSend;
};
});


The test



describe("Category Service Tests", function () {

var myCategoryService, $httpBackend;

beforeEach(module("adminApp"));

beforeEach(inject(function (categoryService,_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.when("GET", "./category/categories").respond(["hello","world"]);
myCategoryService = categoryService;
}));

afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});

it('should not be undefined', function() {
expect($httpBackend).toBeDefined();
});

it("Should not be null", function () {
expect(myCategoryService).toBeDefined();
});

it("Should return all available categories", function () {
$httpBackend.expect("GET",'./category/categories');
var categoriesList = myCategoryService.getAllCategories();
$httpBackend.flush();
console.log(categoriesList);

expect(categoriesList.length).toBe(2);
});


});


asked 24 secs ago

milo

365





Aucun commentaire:

Enregistrer un commentaire