茉莉花测试三元条件

Jasmine Testing Ternary Conditionals

假设我们有以下 JavaScript 代码。

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

我们如何才能在 Jasmine 中为任一场景编写测试?

是否需要两个单独的描述?或者我们能否在测试本身中使用三元条件?

谢谢! 杰里米

我会用两个单独的描述这样

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

    });

考虑以下情况(Angular JS/ES6/Jasmine,控制器 'as' 语法)

代码:

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

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

两个测试用例都通过了。 基本上我们调用 'toggleWidgetView' 方法两次,在每次调用中,条件都会改变 (true/false),就像在现实世界中一样。