I’m trying to write some tests with Jasmine, but now have a problem if there are some code is asynchronous in beforeEach.
The sample code looks like:
describe("Jasmine", function() {
var data ;
beforeEach(function(){
console.log('Before each');
getSomeDataFromRemote(function(res){
data = res;
});
});
it("test1", function() {
expect(data).toBe(something);
console.log('Test finished');
});
});
You can see, in the beforeEach, I want to get some data from remote, and assign it to the data asynchronously.
But in the test1, when I try to verify:
expect(data).toBe(something);
The data is undefined, because getSomeDataFromRemote has not finished yet.
How to fix it?
Just like the async stuff within an
ityou can use therunsandwaitsForin your beforeEach:Although I’m going to assume that it’s because this was test code I think you should probably have the
getSomeDataFromRemotecall inside youritas that’s actually what you’re testing 😉You can see some larger examples in some tests I’ve written for an async API here: https://github.com/aaronpowell/db.js/blob/f8a1c331a20e14e286e3f21ff8cea8c2e3e57be6/tests/public/specs/open-db.js