ajmajmajma
ajmajmajma

Reputation: 14216

Angular, karma/jasmine tests not handling .bind

I am writing unit tests for some of my functions and the tests runner seems to have a problem with a bound function. I am binding a function so I have reference to the this inside an inner function. Here is the code:

                  loadStates: function(name, stateName, options) {

                    if (myModule.getModule(name) !== undefined) {
                        this.prepState(name, stateName, options);

                    } else {
                        var bindForCheck = this.prepState.bind(this);

                        //module cannot be found check for 5 seconds
                        $log.warn("Requesting " + name + "...");
                        var timeToCheck = true;
                        setTimeout(function() {
                            timeToCheck = false;
                        }, 5000);
                        var check = {
                            init: function() {
                                check.checkAgain();
                            },
                            checkAgain: function() {
                                if (timeToCheck) {
                                    if (myModule.getModule(name) !== undefined) {
                                        bindForCheck(name, stateName, options);
                                    } else {
                                        //still doesn't exists
                                        setTimeout(check.checkAgain, 200);
                                    }
                                } else {
                                    //doesn't exist after 5 seconds
                                    $log.error("Requested module (" + name + ") could not be found at this time.");
                                }
                            }
                        };
                        check.init();
                    }

                }

So the issue is with the

 var bindForCheck = this.prepState.bind(this);

Which just lets me call an outer function inside of the check.checkAgain() function.

The test runner is spitting back this error when I try to run the else section of the function

TypeError: 'undefined' is not a function (evaluating 'this.prepState.bind(this)')

Could use some help here, this has me stumped on how to fix this. Thanks!

Upvotes: 2

Views: 1289

Answers (1)

fatbeard
fatbeard

Reputation: 121

You are probably using PhantomJS of version < 2. Here is an issue on github. You gonna have to either update PhantomJS or use polyfill. There is a bower package that should do the trick.

Upvotes: 5

Related Questions