问题
I'm trying to test a prototypal method that returns insights about a dataset I am loading via AJAX.
$.getJSON('../data/bryce.json').done(function(data) {
insights = new Insights(data);
describe("People Method", function() {
console.log('it executes this far');
it("should return complete people data", function() {
console.log('but not this far');
expect(insights.people()).toBeTruthy();
});
});
});
When I run this test suite, describe() executes, but not it(). I'm pretty new to JavaScript testing in general, so I imagine I'm doing something wrong. But I'm not sure what it is.
Also, because the data I'm working with is a huge JSON file, it's not really possible to include it in this file. Nor would it be possible to even provide a sample-size version. Each object in the dataset is hundreds of lines long.
回答1:
Jasmine works off a queuing mechanism and executes all the describe
and it
functions queuing up work to be executed.
Doing work asyncronously in Jasmine requires you to follow a certain pattern.
Jasmine 1.x
describe('some suite', function(){
it('some test', function(){
var data;
//Execute some async operation
runs(function(){
$.get('myurl').done(function(d){ data = d; });
});
//Wait for it to finish
waitsFor(function(){
return typeof data !== 'undefined';
});
//Assert once finished
runs(function(){
expect(data.foo).toBe('bar');
});
});
});
Jasmine 1.x uses a special polling mechanism to keep polling the waitsFor
method until it times out, or returns true, and then executes the final runs
method.
Jasmine 2.x
describe('some suite', function(){
var data;
beforeEach(function(done){
$.get('myurl').done(function(d){
data = d;
//Signal test to start
done();
});
});
it('some test', function(done){
expect(data.foo).toBe('bar');
//Signal test is finished
done();
});
});
Jasmine 2.x is a bit different, as it uses a signaling mechanism to indicate when to start and finish the test. Your specs can take in an optional done
method to use for synchronizing your tests.
If you use the done
method in beforeEach
then it will not start your test until that method is called.
If you use the done
method in your it
function, then the test will not finish until that method has been called.
Both of these can be used to effectively manage asynchronous behavior within your tests.
来源:https://stackoverflow.com/questions/24088884/why-is-jasmine-not-executing-it-on-this-async-test