茉莉测试三元条件

Jasmine Testing Ternary Conditionals

本文关键字:三元 条件 测试      更新时间:2023-09-26

假设我们有以下JavaScript代码。

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

我们如何能够在Jasmine中为这两种场景编写测试?

它需要两个单独的描述吗?或者我们可以在测试本身中有一个三元条件吗?

谢谢!Jeremy

我将使用两个单独的描述,如

// 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/Jastsmine,Controller"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)。