模拟承诺链功能

安妮塔

我正在为角度控制器编写测试用例。我在模拟服务API调用时遇到了一个问题。我的控制器api调用是:

 this.testMe = User.getDetails().then(function (response) {
            this.user = response.data;

        }.bind(this), function (response) {
            console.log("error function mocking")
        });

在我的测试案例中,我想模拟该服务“ User ”的方法“ getDetails ”。所以我的测试用例嘲讽是这样的:

   this.getCurrentUserDetails = function () {
                    var deferred = $q.defer();
                    deferred.resolve({data: 'test'});
                    return deferred.promise;
                };

当我运行测试用例时,它给了我这样的错误:

'undefined'不是函数(在'...}。bind(this)附近,函数(re ...')

就像在我的API调用中一样,存在控制器无法找到的bind()函数。因此,我如何也可以使用bind()函数模拟服务。

菲尔

您正在Function.prototype.bind控制器中使用}.bind(this)位)。PhantomJS 1.x尚未实现,bind()因此您不能在测试运行器中使用它。

您的选择是...

  1. 安装bind-polyfill(最好在Bower中devDependencies)并将其包含在karma.conf.js文件中

  2. 别名 this

    var ctrl = this;
    this.testMe = User.getDetails().then(function (response) {
        ctrl.user = response.data;
    }, function (response) {
        console.log("error function mocking")
    });
    
  3. 如果您使用的是下划线/破折号,请尝试使用该_.bind函数

    this.testMe = User.getDetails().then(_.bind(function (response) {
        ctrl.user = response.data;
    }, this)
    
  4. karma.conf.js文件中使用其他浏览器

    browsers : ['Chrome'],
    
    plugins : [
        'karma-chrome-launcher',
        'karma-jasmine'
    ]
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章