angularjs - 模拟 promise 链函数

标签 angularjs unit-testing jasmine karma-jasmine

我正在为 Angular Controller 编写测试用例。我在模拟服务 API 调用时遇到一个问题。 我的 Controller 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' is not a function (near '...}.bind(this), function (re...')

在我的 API 调用中,有 bind() 函数, Controller 无法找到该函数。那么我怎样才能用bind()函数来模拟服务呢。

最佳答案

您正在 Controller 中使用 Function.prototype.bind(}.bind(this) 位)。 PhantomJS 1.x has not implemented bind()所以你不能在测试运行器中使用它。

您的选择是...

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

  2. 别名

    var ctrl = this;
    this.testMe = User.getDetails().then(function (response) {
        ctrl.user = response.data;
    }, function (response) {
        console.log("error function mocking")
    });
    
  3. 如果您使用下划线/lodash,请尝试使用 _.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'
    ]
    

关于angularjs - 模拟 promise 链函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750218/

相关文章:

angularjs - ZoneAwarePromise 已被覆盖

angular - karma : How to handle multiple calls to a spy that have different responses?

javascript - 在 AngularJS 的 ng-repeat 中执行一个函数

java - PIT Mutation Testing maven插件跳过所有私有(private)方法

javascript - Angular : Updating controller scope variable through a factory variable

javascript - 代码拆分 `import` 破坏了 Jest 测试

c# - 如何在 .NET Core 中测试 Controller

javascript - 错误 : Trying to get the AngularJS injector before it being set

angularjs - 如何使用 angularjs 将单页 PDF 文档转换为预览图像

javascript - Angular1.3 : Access controller function inside recursive directive template?