Wednesday, 15 March 2017

Stubbing a newed up function in Jasmine

I am trying to stub out the Node package 'mobile-detect' so I can test my code in Jasmine.

The library is called in the code like so:

import MobileDetect from 'mobile-detect/mobile-detect';

module.exports = React.createClass({
    isMobileDevice: function() {
        const mobileDetect = new MobileDetect(window.navigator.userAgent);
        return mobileDetect.mobile();
    },
    componentDidMount: function() {
        if (this.isMobileDevice(window)) {
            //do mobile stuff
        }
    },
    render: function() {
        //load react components
    }
};

I am trying to stub out the library like so, but it's not working:

spyOn(window, MobileDetect).andCallFake(function() {
    return {
        mobile: function() { return true; }
    };
});

This is the error:

Error: <spyOn> : function MobileDetect(userAgent, maxPhoneWidth) {
    this.ua = userAgent || '';
    this._cache = {};
    //600dp is typical 7" tablet minimum width
    this.maxPhoneWidth = maxPhoneWidth || 600;
}() method does not exist

I suspect this is because MobileDetect has to be 'newed up' in the production code. It can apparently see the function, but it's not stubbing it out properly. Any ideas?



via Stormdamage

No comments:

Post a Comment