0

Assume we have the following JavaScript code.

object = _.isUndefined(object) ? '' : aDifferentObject.property;

How would we be able to write a test for either scenarios in Jasmine?

Would it require two seperate describe's? Or would we be able to have a ternary conditional in the test itself?

Thanks! Jeremy

2 Answers2

0

I will use two separate describe like this

// System Under Test

    function getObjectValue() {
        return _.isUndefined(object) ? '' : aDifferentObject.property;
    }

    // Tests
        describe('when object is undefined', function() {

        it('should return empty string', function() {
            expect(getObjectValue()).toBe('');
        });

    });

    describe('when object is no undefined', function () {

        it('should return property from different object', function () {
            expect(getObjectValue()).toBe(property);
        });

    });
kodebot
  • 1,718
  • 1
  • 22
  • 29
0

Consider the following case (Angular JS/ES6/Jasmine, Controller 'as' syntax)

Code:

Controller.toggleWidgetView = () => {
        Controller.isFullScreenElement() ? Controller.goNormalScreen() : Controller.goFullScreen();
};

Test cases in Jasmine:

describe('.toggleWidgetView()', function() {
        it('should call goNormalScreen method', function() {
            spyOn(Controller, 'isFullScreenElement').and.callFake(function(){
                return true;
            });
            spyOn(Controller, 'goNormalScreen').and.callThrough();
            Controller.toggleWidgetView();
            expect(Controller.goNormalScreen).toHaveBeenCalled();
        });
        it('should call goFullScreen method', function() {
            spyOn(Controller, 'isFullScreenElement').and.callFake(function(){
                return false;
            });
            spyOn(Controller, 'goFullScreen').and.callThrough();
            Controller.toggleWidgetView();
            expect(Controller.goFullScreen).toHaveBeenCalled();
        });
    });

Both the test cases passed. Basically we are calling the 'toggleWidgetView' method twice and in each invocation, the condition changes (true/false) as it will in real world.

pixlboy
  • 1,452
  • 13
  • 30