我正在为 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()
所以你不能在测试运行器中使用它。
您的选择是...
安装 bind-polyfill (最好在您的 Bower
devDependency
中)并将其包含在您的karma.conf.js
文件中别名
此
var ctrl = this; this.testMe = User.getDetails().then(function (response) { ctrl.user = response.data; }, function (response) { console.log("error function mocking") });
如果您使用下划线/lodash,请尝试使用
_.bind
函数this.testMe = User.getDetails().then(_.bind(function (response) { ctrl.user = response.data; }, this)
在
karma.conf.js
文件中使用不同的浏览器browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-jasmine' ]
关于angularjs - 模拟 promise 链函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750218/