How to write Qunit for attachEventBrowser in UI5

114 Views Asked by At

I have a code snippet for which I have to increase code coverage Following is my controller-

I need to have statements in my qunit for the bold section

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
     "sap/m/MessageToast",
], function (Controller,JSONModel,MessageToast) {
    "use strict";

    return Controller.extend("com.sap.onesm.supplier.ext.slpCard.supplierContactDetails.Main", {
        onInit: function () {
            let cardState={};
            this.getView().setModel(new JSONModel(cardState), "cardState");

            let oEventBus = sap.ui.getCore().getEventBus();
            oEventBus.subscribe("SLPDataChannel", "loadData", this.loadData, this);
            console.log('Supplier contact subscribe.');
            oEventBus.subscribe("SLPDataChannel", "errorData", this.errorData, this);
            let cardSubscribeData = {
                "card": 'supplierContact',
                "subscribed": true
            };
            oEventBus.publish("CardSubscribeChannel", "callVendorAPI", cardSubscribeData);
            setTimeout(()=>this.getAvatarWidth(),100);
        },
        loadData: function(channelId, eventId, oData) {
            console.log('In callback supplierContactDetails.loadData().. ');
            let oController = this;
            var data = oData.vendorData;
            oController.oCard = **oController.getView().getParent().getComponentData().__sapUiIntegration_card;
            oController.oCard.getCardHeader().attachBrowserEvent("click",function(){
                oController.onPressNavToSMContacts(oData.smVendorId, oData.s4Url);
            });**

            let loaderStatus = oController.getView().getModel("cardState");
            if(data[0]!=undefined && data[0]["Primary contact first name"]){
                let name=data[0]["Primary contact first name"];
                name+=data[0]["Primary contact middle name"]? " "+data[0]["Primary contact middle name"]:'';
                name+=data[0]["Primary contact last name"]? " "+data[0]["Primary contact last name"]:'';
                data[0]["contactName"]=name;
                oController.getView().setModel( new JSONModel(data[0]), "supplierContact");
                loaderStatus.setProperty("/status", 1);
            }else{
                loaderStatus.setProperty("/status", 2);
            }
            return data[0];
        },
        errorData: function(channelId, eventId, oData) {
            console.log('In callback supplierContactDetails.errorData().. ');
            let controller = this;
            let oModel = controller.getView().getModel("cardState");
            oModel.setProperty("/status", 3);
            console.log("error for " + oData.smVendorId + " : " + oData.error);
        }
    });
});

Following is my test File

QUnit.module("Supplier Contacts Card");
    let oController = new SupplierContactController();

    oController.getView = function() {
        return {
            setModel: function(){},
            getModel: function(){
                return {
                    setProperty: function () { }
                }
            },
            getParent: function () { 
                return {
                    getComponentData: function() {
                    }
                }      
            }
            
        };
    };

    QUnit.test("check for data", function(assert) {

        let expectedVendorData = [{"Supplier Name":"Ariba Supplier Risk Demo Supplier 111620",
                                    "SM Vendor ID":"S25187250",
                                    "Primary contact first name": "Drew",
                                    "Primary contact last name": "Myers",
                                    "Primary contact email": "[email protected]"}];
        let expectedOData = {"vendorData" : expectedVendorData, 
        "smVendorId": "S25187250", 
        "s4Url": "sampleURL"};

        oController.onInit();
        let loadDataResult = oController.loadData("", "", expectedOData);
        assert.strictEqual(loadDataResult[0][["contactName"]],"Drew Myers","Contact Name Matched");
        assert.strictEqual(loadDataResult[0][["Primary contact email"]],"[email protected]","Email Id Matched");
    });

I am getting the follwoing error

Died on test #1     at QUnit.test (https://ui5.sap.com/resources/sap/ui/thirdparty/sinon-qunit.js:34:356)
    at http://localhost:8080/test/unit/controller/SupplierContacts.controller.js:27:11
    at https://ui5.sap.com/resources/sap-ui-core.js:10:16806: Cannot read properties of undefined (reading '__sapUiIntegration_card')@ 1 ms
Expected:   
null
Message:    Diff suppressed as the expected and actual results have an equivalent serialization
Source:     
TypeError: Cannot read properties of undefined (reading '__sapUiIntegration_card')
    at p.loadData (http://localhost:8080/ext/slpCard/supplierContactDetails/SupplierContact.controller.js:28:85)
    at Object.<anonymous> (http://localhost:8080/test/unit/controller/SupplierContacts.controller.js:39:42)
    at Object.i (https://ui5.sap.com/resources/sap/ui/thirdparty/sinon.js:220:476)
    at Object.e (https://ui5.sap.com/resources/sap/ui/thirdparty/sinon.js:220:794)

how do I stub attachBrowserEvent

I tried to initialize the controller in this manner

let oController = new SupplierContactController();

    oController.getView = function() {
        return {
            setModel: function(){},
            getModel: function(){
                return {
                    setProperty: function () { }
                }
            },
            getParent: function () { 
                return {
                    getComponentData: function() {
                    }
                }      
            }
            
        };
    };

but now stuck at getComponentData, don't know what to do after that

1

There are 1 best solutions below

0
p_efros On

You first need to find out what kind of Object is returned by getCardHeader(). For this, you can put a debugger point in your original code and check the metadata of the object (put a debugger point on the line and execute:

oController.getView().getParent().getComponentData().__sapUiIntegration_card.getCardHeader()

Then, knowing what kind of object it is, you can either stub it (create a stub for that object (so getCardHeader() would return the stub) and verify that the attachBrowserEvent method was called on it or you can just create your own dummy object that contains the method attachBrowserEvent if you just want the code to be executed without errors.