A
A
Alexis178422016-05-16 20:38:46
JavaScript
Alexis17842, 2016-05-16 20:38:46

Is it possible to manipulate time via jasmine.clock() when testing asynchronous functions?

Good day.
I am mastering the manual on BDD with the help of Jasmine.
There is a great opportunity to test functions like setTimeout() using jasmine.clock(), but in synchronous mode.
Is it possible to manipulate time via jasmine.clock() when testing async functions when done() call is used?

Here, let's say, below is the code based on the examples of the tutorial. Is it possible with jasmine.clock() to reduce the callback waiting time and, if so, how to do it correctly?

describe("long asynchronous specs", function() {
    var value;
    
  beforeEach(function(done) {
    jasmine.clock().install();
    });
     
  beforeEach(function(done) {
    value = 0;
    done();
    }, 10000);
  jasmine.clock().tick(10001);// чтобы не ждать 10 с в предыдущем блоке beforeEach
    it("takes a long time", function(done) {
    setTimeout(function() {
      value++;
      expect(value).toBeGreaterThan(0);
      done();
    }, 9000);
     //jasmine.clock().tick(9001);
    }, 10000);
  jasmine.clock().tick(10001);// чтобы не ждать 10 с в предыдущем блоке beforeEach
  afterEach(function(done) {
    done();
  }, 1000);
  afterEach(function(done) {
    jasmine.clock().uninstall();  
  });
  
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexis17842, 2016-05-17
@Alexis17842

I seem to have found the answer to my question.
For those who are interested, I share:

describe("clock pollution", function() {
    var value;
  it("async with clock", function(done) {
      jasmine.clock().install()
      setTimeout(function() {
        value = 1;
    expect(value).toBeGreaterThan(0);
    jasmine.clock().uninstall()
        done()
      }, 20000)
      jasmine.clock().tick(20001)
    })
})

Or a variant with promises:
function delay(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms)
  })
}

describe("clock pollution", function() {
  var value;
  it("async with clock", function(done) {
    jasmine.clock().install()
    delay(2000)
      .then(function() {
        value = 1;
        expect(value).toBeGreaterThan(0);
        jasmine.clock().uninstall()
        done()
      })
    jasmine.clock().tick(2001)
  })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question