简体   繁体   中英

Jasmine async testing without settimeout

I'm looking to create some jasmine specs for a piece of code that has async functionality.

In the jasmine docs it shows the example:

it("takes a long time", function(done) {
          setTimeout(function() {
            done();
          }, 9000);
        });

Using the done function and a setTimeout, my issue with this is setTimout could be fragile ie delays in test runs in enviros

is there an alternative solution to such tests where I don't have to use a timeout?

Thanks in advance

In this example setTimeout is actually the function being tested. It's used as a representative example of an asynchronous function. The key point is that you must explicitly call done() when your test is complete. Your code should look something like:

it("takes a long time", function(done) { myMethod('foo', 'bar', function callback() { assert(...) done(); }); // callback-style }

it("takes a long time", function(done) { myMethod('foo', 'bar').then(function() { assert(...) done(); }); // promise-style });

it("takes a long time", async function(done) { await myMethod('foo', 'bar') assert(...) done() });

The documented function is intended to illustrate using the done callback following a long-running method, and should not be used for actual tests.

Normally, you would expect a long running function to be supplied with a callback in which you would call the done function. For example, you could write a unit test involving a file that took a long time to write data:

it("writes a lot of data", function(done) {
  var fd = 999; // Obtain a file descriptor in some way...

  fs.write(fd, veryLongString, function (err, written, string) {
    // Carry out verification here, after the file has been written
    done();
  });

Again, this is only illustrative, as you would generally not want to write to a file within the body of a unit test. But the idea is that you can call done after some long-running operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM