0

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?

Stormdamage
  • 389
  • 1
  • 5
  • 16
  • Does `spyOn(window, 'MobileDetect')...` change the error? – dan Mar 15 '17 at 16:44
  • Good call, but now I get ` : MobileDetect() method does not exist`. – Stormdamage Mar 16 '17 at 08:48
  • Have you seen this - http://stackoverflow.com/questions/35240469/how-to-mock-the-imports-of-an-es6-module? This implies that `spyOn(MobileDetect, 'default')` might do the trick? – dan Mar 16 '17 at 09:00

0 Answers0