Reputation: 4562
I am learning testing with Jasmine and I'm looking for a bit of clarification on async
testing to further my understanding.
In the following code, the test in the first spec works but the second version where I've removed the beforeEach
and moved the async calls into the it
does not.
describe("Working Asnc", function() {
var value = 0;
function funcRunInBackground() {
value = 1;
};
function wrapFuncRunInBackground(done) {
setTimeout(function() {
funcRunInBackground();
done();
}, 2000);
}
beforeEach(function(done) {
wrapFuncRunInBackground(done);
});
it("should be greater than 0", function() {
expect(value).toBeGreaterThan(0);
});
});
describe("Not working Asnc", function() { var value = 0;
function funcRunInBackground() {
value = 1;
};
function wrapFuncRunInBackground(done) {
setTimeout(function() {
funcRunInBackground();
done();
}, 2000);
}
it("should be greater than 0", function(done) {
wrapFuncRunInBackground(done);
expect(value).toBeGreaterThan(0);
});
});
Can we do the asnc operation from with the test itself if this is ever required?
Upvotes: 0
Views: 52
Reputation: 885
You can not syncronize js async code that way. You just can not wait for async code would be executed without using zallbacks/promises/co+generators/etc. In your case it should be something like:
it("should be greater than 0", function(done) {
wrapFuncRunInBackground(function(){
expect(value).toBeGreaterThan(0);
done();
});
});
Upvotes: 1
Reputation: 349222
Change
it("should be greater than 0", function(done) {
wrapFuncRunInBackground(done);
expect(value).toBeGreaterThan(0);
});
to
it("should be greater than 0", function(done) {
wrapFuncRunInBackground(function() {
expect(value).toBeGreaterThan(0);
done();
});
});
Callbacks don't pause the execution, so in your original snippet there is nothing that prevents the expect(...)
call from being run before the asynchronous callback of wrapFuncRunInBackground
is called.
done
is not magic, it's just a normal function that marks the test as completed upon invocation...
Upvotes: 1