Search code examples
unit-testingjasminebddjasmine2.0

Async Test in Jasmine 2.6


The syntax for async tests has changed since 2.x and the documentation is not clear.

Can someone clarify how I execute some code, block for 3 seconds, and then run a test condition using the new syntax?

it('should update the table when new data is provided', function() {
  var newData = ",0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23\nX-Y,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1";

  fixture.datum(csv).call(fp);

  expect(fp.dataset()).toEqual(csv);

  fp.dataset(newData);

  expect(fp.dataset()).toEqual(newData);

  //block for 3 seconds
  expect(fixture.selectAll(".row").nodes().length).toBe(3);

});

Solution

  • done needs to be passed as a parameter to a spec, and done() needs to be called as the last statement in the setTimeout() block.

    If the async spec exceeds 5sec in total, it will fail, see jasmine docs excerpt for more info:

    By default jasmine will wait for 5 seconds for an asynchronous spec to finish before causing a timeout failure. If the timeout expires before done is called, the current spec will be marked as failed and suite execution will continue as if done was called.

    If specific specs should fail faster or need more time this can be adjusted >by passing a timeout value to it, etc.

    it('should update the table when new data is provided', function(done) {
      var newData = ",0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23\nX-Y,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1";
    
      fixture.datum(csv).call(fp);
    
      expect(fp.dataset()).toEqual(csv);
    
      fp.dataset(newData);
    
      expect(fp.dataset()).toEqual(newData);
    
      //block for 3 seconds, then execute expect
      setTimeout(function() {
          expect(fixture.selectAll(".row").nodes().length).toBe(3);
          done(); //dont forget!!
      }, 3000);
    
    });