Search code examples
unit-testingember.jsjqxgrid

Unit test jqgrid action


I need to verify that the jqxgrid's 'rowClicked' action gets called using mocha unit tests in EmberJS. I have a grid initialized and can verify that it gets rendered, rows and headers are rendered, but I'm stuck on the rowclick event. I use jQuery to simulate a click on a row like this:

this.$('#row0grid_testgrid').trigger('click');

My grid code listens for the rowClick event like this:

this.grid().on('rowclick', function(evt) {
        // My code here
    });

How can I verify that this gets called? Thanks


Solution

  • Can you do something like this - mocking functions?

    /*** in your unit test ***/
    //... get your grid object ...
    const gridComponent = ....
    
    // save the original function to assign it later back
    const originalOn = gridComponent.on;
    
    // now mock the on function
    gridComponent.on = function(actionName, handler){
    assert.ok(true, "on() function has been called");
    
    assert.equal(actionName, "rowclick", "the action on which on() function has been triggered is correct");
    }
    
    // execute tested context
    this.$('#row0grid_testgrid').trigger('click');
    
    // tidy up
    gridComponent.on = originalOn;
    

    There are few things to mention here: if this works, you will test that on() has been called and that it was triggered on correct action 'rowclick'. However, you are still not able to test the part of your code "// My code here", within evented function.

    If you want to test your evented function, what you can do is to call anonymous function from it. Let me show you what I mean:

    /*** your component code ***/
    // this will be called on "rowclick"
    myComponentFunction: function(whatArgument){
      // My code here
    }
    
    ....
    const self = this;
    this.grid().on('rowclick', function(evt) {
            // instead of pure code call a function
            const someParameters = "foo";
            self.myComponentFunction(someParameters);    
    });
    ...
    

    In your unit test you are then able to mock also myComponentFunction:

    // same unit test
    ....
    const originalMyComponentFunction = gridComponent.myComponentFunction;
    
    gridComponent.myComponentFunction = function(arg){
    assert.ok(true, "myComponentFunction() has been called!");
    
    // test argument, whatever
    assert.equal(arg, "foo", "argument passed to myComponentFunction() from an event triggered on 'rowclick' is correct");
    }
    
    // tidy up myComponentFunction mock, too.
    gridComponent.myComponentFunction = originalMyComponentFunction;
    

    Btw, prefered way to set up mocks and tidy them up are to put it into beforeEach() and afterEach(), look at the ember-cli testing guides.

    If you have any better idea how to test this, I would like to learn from you, too :)