How can I stub methods attached to the 'this' object using Sinon.js?

1.5k views Asked by At

I'm attempting to test the 'onInit' function attached below:

function (jQuery, Controller, JSONModel) {
        "use strict";

        var controls;

        var mainController = Controller.extend("tool.controller.Main", {

            onInit: function(oEvent) {

                var inputModel = new JSONModel("./model/inputs.json");
                var productsModel = new JSONModel("./model/products.json");

                this.getView().setModel(inputModel, "inputModel");
                this.getView().setModel(productsModel);

                controls = viewControls.main.apply(this);
            },
...

Objective

For this function in particular, I simply need to test that the 'setModel' and 'main' methods get called.

The Problem I'm facing

There are a few dependencies that I need to stub/mock in order to consider this 'onInit' function properly unit tested. Specifically those dependencies would be would be the following:

  • 'this' keyword/object that has a 'getView' method attached to it

  • 'JSONModel' object constructor

I'm stuck with understanding how I can mock the aforementioned. Below is what I have tried with my beginner level understanding of Sinon.js:

QUnit.test("'onInit' Function Test", function(assert) {

          // Arrange   
         var JSONModel = sinon.stub();  
         var inputModel = sinon.stub();
         var productsModel = sinon.stub();

         //spies- what methods are we asserting get called?
         var setModel = sinon.spy();
         var main = sinon.spy()

         //stubs- what dependencies are we 'faking'
        sinon.stub(this, 'getView').returns({setModel});

         // Act 
         mainController.onInit();

         // Assert 
         assert.ok(setModel.called, "setModel called");
         assert.ok(main.called, "setModel called");


        });

I'm pretty sure there is a better approach as this might be completely the wrong strategy. Your suggestions will greatly be appreciated as I learn unit testing in its entirety. Here is the error I get if it helps:

enter image description here

0

There are 0 answers