yukatan / commangular

Command framework for AngularJS
MIT License
83 stars 8 forks source link

No command unit test documentation #13

Closed mscharp closed 9 years ago

mscharp commented 9 years ago

Currently, there is a section in your documentation for Unit testing commands, but it is empty. I figured out how to test them, so I thought I would post what I've done in case it helps anyone. Also, if you think it could be done better/easier I would appreciate the feedback. Thanks

Command:

commangular.create( 'Command1', function ( $log, $commangular )
{
    return {
        execute: [ 'FuncParam1', function ( funcParam )
        {
            // some functionality here
            var something = [];
            return something;
        }],
        onResult: function ( arry )
        {
            //do something here with arry
            $commangular.dispatch('anEvent', {arry: arry});
        }
    }
} );

Test:

"use strict";

describe( "AddProcessesToQueueCommand", function ()
{
    var commProvider, commangular, command, commandBody;

    beforeEach( function()
    {
        module( 'commangular', function ( $commangularProvider )
        {
            commProvider = $commangularProvider;
        } );
        module('myModuleToTest');
        inject( function ( $log, $commangular )
        {
            command = commProvider.findCommand('myEventName').
                      descriptors[0].command.commandFunction;
            commandBody = command( $log, $commangular );
        } );
    });

    it('should do something in the execute function', function()
    {
        expect( commandBody ).toBeDefined();

        //given my command setup,
        //execute is an array with the function being the last item.
        //I imagine without the array notation in the command
        // it could be called via commandBody.execute('asdf');
        var result = commandBody.execute[1]( 'asdf' );

        expect( result.length ).toEqual( 0 );
    });

    it('should do something in the onResult function', function()
    {
        spyOn( commangular, 'dispatch' );
        commandBody.onResult( [] );
        expect( commangular.dispatch ).toHaveBeenCalledWith( 'anEvent', {arry: []} );
    });
});
yukatan commented 9 years ago

You can check out the test in commangular test folder. These test are using commangular-mocks to dispatch events or groups easily. Commangular-mocks add a dispatch method to the window,so you don't need to use $commangular object.