qUnit тестирование на закрытие jQuery - PullRequest
0 голосов
/ 16 января 2019

У меня проблемы с выполнением qUnit для кода с замыканием.

Быстрый обзор, я использую qUnit 2.5.0 и sinon 4.3.0.

sinon не может обнаружить функцию iWantToTestThisOne_1() из файлов JsFileToTest_1.js и JsFileToTest_2.js.

Так что сейчас я не могу заполучить это закрытие

Другое дело, что в JsFileToTest_2.js даже не замыкание, а всего лишь alias из $(document).ready(function{});. все же sinon не может определить функции внутри него.

Как я понимаю, sinons берет методы из window объекта. Как я проверяю window объект. Функции, определенные в JsFileToTest_2 .js and JsFileToTest_2.js`, не были присоединены к нему.

Однако, когда я пытаюсь удалить (function($) { })(jQuery); и $(function() {});, функции уже были прикреплены к window объекту.

Мой вопрос: как мне выполнить тестирование qUnit, если функции содержатся в замыкании (function($) { })(jQuery); или $(function() {});. У меня проблемы с пониманием того, как прикреплены функции. Кроме того, это может быть потому, что я не совсем понял, как заглушить функции через sinon.

См. Примеры ниже

JsFileToTest_1.js

(function($) {
    function iWantToTestThisOne_1() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_2() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_3() {
        //do something
        doSomething();
    }

    function doSomething() {
        //doing something
    }
})(jQuery);

JsFileToTest_2.js

$(function() {
    function iWantToTestThisOne_1() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_2() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_3() {
        //do something
        doSomething();
    }

    function doSomething() {
        //doing something
    }
});

qUnitTestCode.js

QUnit.test('iWantToTestThisOne_1()', function(assert){
    stub_doSomething = sinon.stub(window, "doSomething").returns("something");

    assert.equal(stub_doSomething.called, true, "doSomething() is called");
});

QUnit.test('iWantToTestThisOne_2()', function(assert){
    stub_doSomething = sinon.stub(window, "doSomething").returns("something");

    assert.equal(stub_doSomething.called, true, "doSomething() is called");
});

QUnit.test('iWantToTestThisOne_3()', function(assert){
    stub_doSomething = sinon.stub(window, "doSomething").returns("something");

    assert.equal(stub_doSomething.called, true, "doSomething() is called");
});

1 Ответ

0 голосов
/ 18 января 2019

К сожалению, вы не можете проверить их, используя код, как он у вас есть. Эти функции являются частными для области действия функции обертывания (недоступны за ее пределами). Однако вы можете реорганизовать свой код, чтобы это произошло:

// module 1
function initSomethings($) {  // <-- notice I added a name
    function iWantToTestThisOne_1() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_2() {
        //do something
        doSomething();
    }

    function iWantToTestThisOne_3() {
        //do something
        doSomething();
    }

    function doSomething() {
        //doing something
    }

    return { // give back the methods in here...
        iWantToTestThisOne_1,
        iWantToTestThisOne_2,
        iWantToTestThisOne_3,
        doSomething
        // Note that we don't have to return ALL of them, so you could keep some of them private by not returning them here
    };
};  // <-- notice that I am NOT calling the wrapper function

Затем, в каком-то «главном» модуле, мы можем инициализировать наши функции:

// "main" module
initSomething();
initAnother();

Это заботится о коде вашего приложения. Для тестирования мы можем использовать возвращаемое значение всех функций:

QUnit.test('iWantToTestThisOne_1()', function(assert){
    // Start by initializing your functions...
    let methods = initSomething();
    // Then stub it out...
    let stub_doSomething = sinon.stub(methods, "doSomething").returns("something");

    // Now you call the function you're testing:
    methods.iWantToTestThisOne_1();
    // And do your assertions
    assert.equal(stub_doSomething.called, true, "doSomething() is called");
    // more assertions...
});
...