所以我试图在我的角度应用程序测试中得到承诺,谁能弄清楚我在这里做错了什么,它不断返回:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
我不知道是不是$q。
仅供参考,我也尝试了it('test', function(done){... done();})
控制器
(function() {
'use strict';
angular
.module('controller.editor', [])
.controller('EditorController', EditorController);
function EditorController($scope, $q) {
var vm = this;
angular.extend(vm, {
hack: hack
});
function hack(bool) {
return $q(function(resolve, reject) {
if (bool) {
resolve(true);
}
reject(false);
});
}
}
});
测试
describe('EditorController', function() {
var vm, scope, $controller, $rootScope, $injector;
beforeEach(function() {
module('app');
//Inject
inject(function(_$injector_) {
$injector = _$injector_;
$controller = $injector.get('$controller');
$rootScope = $injector.get('$rootScope');
// Create new scope object
scope = $rootScope.$new();
// Bind the controller
vm = $controller('EditorController', {
$scope: scope
});
});
});
describe('#addCustom', function() {
it('test', function(done) {
var aHack = vm.hack(true);
aHack.then(function(bool){
// Resolve
expect(bool).to.be.eq(true);
done();
}, function() {
// Reject
expect(bool).to.be.eq(false);
done();
});
});
});
});
在 angular 中测试承诺时,最佳做法是依靠角度机制来完成其工作以同步而不是异步方式解析承诺。
这使得代码更易于阅读和维护。
它也不太容易出错;在.then()
中执行断言是一种反模式,因为如果从未调用回调,您的断言将永远不会运行。
要使用角度测试方式,您应该:
- 删除
done
- 在测试中做
$rootScope.$digest()
以解决承诺 - 做你的断言
将其应用于您的代码将是:
describe('#addCustom', function() {
it('test', function() {
var __bool = false;
var aHack = vm.hack(true).then(function(bool) {
__bool = bool;
});
$rootScope.$digest();
expect(__bool).to.be.eq(true);
});
});
但这很棘手,因为$rootScope.$digest
只解析$q
承诺,而不是所有承诺,尤其是不是通过各种 es5 填充码Promise()
构造函数创建的承诺,请参阅以下内容:
承诺在 angularjs 茉莉花测试中解决得太晚了
另请参阅:
http://brianmcd.com/2014/03/27/a-tip-for-angular-unit-tests-with-promises.html
问题是你的承诺在你设置"then"行为之前就已经解决了。
看看这些都使用 setTimeout 的示例。