如果您有多个beforeEach
,它们会始终运行吗?
beforeEach(function() {});
beforeEach(function() {});
beforeEach(function() {});
beforeEach(function() {});
beforeEach(function() {});
看来他们会的。我尝试用我的代码对其进行测试:
describe('Directive: Statement', function() {
var el, scope, statements;
beforeEach(module('simulatedSelves'));
beforeEach(module('templates'));
beforeEach(inject(function($compile, $rootScope) {
console.log(1);
scope = $rootScope.$new();
statements = [];
scope.statement = {
text: 'test',
arr: []
};
scope.statement.parent = statements;
statements.push(scope.statement);
el = angular.element('<statement statement=statement></statement>');
$compile(el)(scope);
scope.$digest();
}));
beforeEach(function() {
var counter = 0;
console.log(2);
for (var i = 0; i < 1000000; i++) {
counter++;
}
console.log(counter);
});
beforeEach(function() {
console.log(3);
});
it('test statement has correct properties', function() {
// stuff
});
});
它记录:
1
2
1000000
3
由于带有较长
beforeEach
循环的for
在记录3
之前先将其内容注销,因此我认为beforeEach
可以同步运行。真的吗? 最佳答案
是的,所有beforeEach
都将按照您定义的顺序执行。
如果您深入研究Jasmine,最终将获得this definition:
Suite.prototype.beforeEach = function(fn) {
this.beforeFns.unshift(fn);
};
添加
describe
时,Suite
会生成并嵌套。每个Suite
都使用this.beforeFns = []
初始化,如您所见,它已添加到其中。请注意,unshift
添加到了数组的左侧,因此您希望稍后定义的beforeEach
首先运行。当 Jasmine 走到 child 套房的 parent 那里,收集所有beforeEach
列表,然后反转它们以您想要的顺序运行时,它就是fixed later。var beforeAndAfterFns = function(suite) {
return function() {
var befores = [],
afters = [];
while(suite) {
befores = befores.concat(suite.beforeFns);
afters = afters.concat(suite.afterFns);
suite = suite.parentSuite;
}
return {
befores: befores.reverse(),
afters: afters
};
};
};
像Dan points out一样,到目前为止,我们假设您的所有
beforeEach
都是同步的。从Jasmine 2开始,您可以像这样设置异步beforeEach
:beforeEach(function(done) {
setTimeout(function() {
console.log('Async');
done();
}, 1000)
});
在运行时,Jasmine向您发送
done
函数,并异步执行if your function takes an argument。 (Function.length返回函数期望的参数数量)。for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) {
var queueableFn = queueableFns[iterativeIndex];
if (queueableFn.fn.length > 0) {
attemptAsync(queueableFn);
return;
} else {
attemptSync(queueableFn);
}
}
attemptAsync
等待您调用done()
,然后QueueRunner
移至下一个beforeEach
钩子(Hook),因此排序仍然有效!挺整洁的。describe('beforeEach', function() {
var data = null;
beforeEach(function() { data = []; });
beforeEach(function() { data.push(1); });
beforeEach(function(done) {
setTimeout(function() {
data.push('Async');
done();
}, 1000);
});
beforeEach(function() { data.push(2); });
beforeEach(function() { data.push(3); });
it('runs in order', function(){
expect(data).toEqual([1, 'Async', 2, 3]);
});
});
关于javascript - Jasmine 的beforeEach同步吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31492452/