Javascript 《卡玛摩卡》中带有$q和棱角的承诺;柴
因此,我试图在我的angular应用程序测试中获得工作承诺,有人能找出我做错了什么吗Javascript 《卡玛摩卡》中带有$q和棱角的承诺;柴,javascript,angularjs,karma-runner,karma-mocha,Javascript,Angularjs,Karma Runner,Karma Mocha,因此,我试图在我的angular应用程序测试中获得工作承诺,有人能找出我做错了什么吗 Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test. 我不知道是不是q美元 FYI我还尝试了it('test',函数(done){…done();}) 控制器 (function() { 'use strict'; angular .module(
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
我不知道是不是q美元
FYI我还尝试了it('test',函数(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();
});
});
});
});
问题是你的承诺在你设定“然后”行为之前就已经解决了
看看所有人都使用setTimeout。问题是,在设置“then”行为之前,您的承诺已经得到了解决
看一看,所有这些都使用setTimeout。在角度测试承诺时,最佳做法是依靠角度机制来完成同步而不是异步解析承诺的工作 这使得代码更易于阅读和维护 它也不太容易出错;在
.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
承诺,而不是所有承诺,特别是通过Promise()
构造函数从各种es5垫片创建的承诺,请参见以下内容:
另见:
在角度测试承诺时,最好的做法是依靠角度机制来完成同步而不是异步解析承诺的工作 这使得代码更易于阅读和维护 它也不太容易出错;在
.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
承诺,而不是所有承诺,特别是通过Promise()
构造函数从各种es5垫片创建的承诺,请参见以下内容:
另见:
请确保文本准确描述了当前情况。对于您发布的代码片段,您是否真的收到消息
Error:超时超过2000ms。确保在此测试中调用了done()回调。
?您在代码段设置中的任何地方都没有使用done
。返回承诺应该是相同的,但我已更新了它。请确保文本准确描述了当前情况。对于您发布的代码片段,您是否真的收到消息Error:超时超过2000ms。确保在此测试中调用了done()回调。
?您在代码段设置中的任何地方都没有使用done
。return承诺应该是相同的,但我更新了它