tester123
tester123

Reputation: 1113

Jasmine Test $log Decorator

I have a decorator that is (currently) creating an object using $log.error data and logging it to the console. It will eventually be sent to the server.

I am having a really hard time testing this $provider with Jasmine.

I keep getting an error saying

TypeError: 'undefined' is not an object (evaluating '$log.info.logs.push')

It's for this line

original.apply($delegate, data);

Provider:

$provide.decorator('$log', [
    '$delegate',
    function($delegate){
        var levels = ['debug', 'info', 'warn', 'error'],
            contentType = 'application/json; charset=UTF-8';

        _.each(levels, function(level) {

            // storing the original function
            var original = $delegate[ level ];

            // creating a wrapped version of each $log level function
            $delegate[ level ] = _.wrap(original, function(original) {

                // logger data to be sent/logged to console
                var data = Array.prototype.slice.call(arguments, 1);
                // call to the original function which will write to the console
                original.apply($delegate, data);

                var postData = { date: moment(new Date()).toISOString(), level: level, message: data[ 0 ].message, stack: data[ 0 ].stack };

                console.log(postData);
            });
        });
        // returning to $log object with the new wrapped log-level functions
        return $delegate;
    }
]); 

Jasmine Test

describe('$log decorator', function() {

    var $log;
    beforeEach(module('ngMock'));
    beforeEach(module('myApp'));

    beforeEach(inject(function(_$log_) {
        $log = _$log_;
    }))

    it('should contain the error', function() {
        var exception = {
            message: "Error Message",
            stack: "Error Stack"
        };

        $log.error(exception);

        dump($log.error)
        expect($log.error).toBeDefined();

    });
});

Upvotes: 3

Views: 791

Answers (1)

Jimmy
Jimmy

Reputation: 21

You can try to reset the $log before you inject to your test/controller by calling

$log.reset()

This will set

log.info.logs = []

So you don't get the error anymore. Also your test can be more aggressive

expect(log.error.logs).toContain(['Error Message']);

Hope it helps.

Upvotes: 2

Related Questions