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

旧街凉风 提交于 2019-12-24 01:14:27

问题


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:

来源:https://stackoverflow.com/questions/41272975/how-can-i-stub-methods-attached-to-the-this-object-using-sinon-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!