茉莉花测试三元条件

时间:2015-03-18 01:55:02

标签: javascript testing jasmine istanbul

假设我们有以下JavaScript代码。

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

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

它需要两个独立的描述吗?或者我们能否在测试中有三元条件?

谢谢! 杰里米

2 个答案:

答案 0 :(得分:0)

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

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

    });

答案 1 :(得分:0)

考虑以下情况(Angular JS / ES6 / Jasmine,Controller'作为'语法)

代码:

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),就像在现实世界中一样。

相关问题