1

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 i.e. 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

2
  • how you calculate result of async function - by callback, promise or await? Commented Jan 16, 2017 at 16:13
  • Take a look at jasmine-co. With this npm package you can use yield and drop setTimeout() and done(). Commented Jan 16, 2017 at 16:28

2 Answers 2

1

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() });

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.