mardi 5 juillet 2016

Jasmine unit tests with promises

I'm new at angular and at unit testing with angular. We are using odata for database CRUD actions, so we have created a service for that, looks like this:

function DatabaseService($http, $odataresource, DateFactory, constants) {

    var url = constants.BACKEND.URL;
    var ObjCreate = $odataresource(url + 'Objects/Function.CreateObject', {}, {}, {});

    var service = {
        createSomething: {
            createObj: createObj
        }};

    return service;

    function createObj(formData) {
        var myObj = new ObjCreate();
        mapData(formData, myObj );
        return myObj.$save();
    }

The code is a bit abstracted for my question, so don't wonder please. I want to unit test the function createObj() now, which doesn't work. I took an angular class and we learned there that for 'execute' promises we have to use $rootScope.digest(), but it doesn't seem to work in my case:

    describe('createObj', function () {

    it('should return data', inject(function ($rootScope) {

        var DatabaseService = $injector.get('DatabaseService', { $odataresource: $odataresource });

        var formDataMock = {
            productName: "Produktname"
        };

        var test = 'abc';

        DatabaseService.createSomething.createObj(formDataMock)
            .then(function (data) {
                test = data;
            })
            .catch(function (error) {
                test = error;
            });

        $rootScope.$digest();

        console.log(test);
    }));

I have added the setting of the variable test to see when for example the then path is executed, but even with the $rootScope.$digest it will never step into the then path, my variable test will never change from 'abc' to something else.

Could you please give me a hint what am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire