Angular, karma/jasmine 测试不处理 .bind

ajm*_*jma 2 javascript angularjs karma-runner karma-jasmine

我正在为我的一些函数编写单元测试,而测试运行器似乎有一个绑定函数的问题。我正在绑定一个函数,所以我在内部函数中引用了 this 。这是代码:

                  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();
                    }

                }
Run Code Online (Sandbox Code Playgroud)

所以问题在于

 var bindForCheck = this.prepState.bind(this);
Run Code Online (Sandbox Code Playgroud)

这只是让我在 check.checkAgain() 函数内部调用一个外部函数。

当我尝试运行函数的 else 部分时,测试运行器正在吐出这个错误

TypeError: 'undefined' is not a function (evaluating 'this.prepState.bind(this)')
Run Code Online (Sandbox Code Playgroud)

可以在这里使用一些帮助,这让我很难解决这个问题。谢谢!

小智 5

您可能正在使用版本 < 2 的 PhantomJS。这是github 上的一个问题。您将不得不更新 PhantomJS 或使用 polyfill。有一个凉亭包应该可以解决问题。