Search code examples
yui

YUI .. call one javascript function from another java script


I have started writing unit tests. I need to call a function in signup.js from another script, unittest.js. How can I do this?

Unittest.html would incorporate both scripts.

 <html>
 <head>

 <script scr ="signup.js"></script>
 <script src="unittest,js"></script>

</head>
</html>

This is signup.js, which I have to test.

YUI.use(function(Y){

    demo : function(){

        window.alert('hello);
    }

});

unittest.js:

YUI.use(function(Y){
 var abc = new Y.Test.case(

   testOk : function(){


      demo();                // Calling this function but not working 
     <Some_Assestion_Stuff_Here>

  }

   );


});

Solution

  • Your two scripts have both created a YUI sandbox. Neither sandbox share anything with the other, so you cannot achieve unit testing demo() like this.

    What you can do is to register a module in signup.js and use it in unittest.js. See the following example: http://jsfiddle.net/746nq/

    In signup.js, create the module:

    // Create a YUI module in signup.js.
    YUI.add('signup', function (Y) {
       // Write your module code here, and make your module available on the Y
       // object if desired.
       Y.Signup = {
           demo: function () {
               window.alert("Demo!");
           }
       };
    });
    

    In unittest.js, use the module:

    // Create a YUI sandbox in unittest.js and use our newly created module
    YUI().use('signup', function (Y) {
        Y.Signup.demo();
        // assert stuff
    });
    

    Hope this helps you.