Ryan Shocker
Ryan Shocker

Reputation: 703

How to force a function to execute first in Jasmine test?

I have a route in Node that gets an auth key. I want to use this auth key in all my jasmine tests as a parameter in the URL request. I want SetUp function to run, set a global var, then allow me to use this variable in all the rest of the test cases.

SetUp Function

    var global_key = request({
      uri               : 'http://localhost:3000/grabToken',
      method            : 'GET'
    },
    function (err, body, res) {
      if (err) { console.log(err);}
      else {
        return body['auth_key'];
      }
    });

Test Suite

function testCases() {
  describe(TEST_SUITE, function() {
    describe("GET /retrieveSecret/VALID_UUID", function() {
      it('Requests the secret - Successful response', function(done) {
        // ...
      }
    }
  }
}

Upvotes: 0

Views: 297

Answers (1)

You could use asynchronous version of beforeAll function:

describe(TEST_SUITE, function() {
    let key;

    beforeAll(function (done) {
        const params = { uri: 'http://localhost:3000/grabToken', method: 'GET' };

        request(params, function (err, body, res) {
            if (err) {
                console.log(err);
                done.fail();
            } else {
                key = body['auth_key'];
                done();
            }
        });
    })

    describe("GET /retrieveSecret/VALID_UUID", function() {
        it('Requests the secret - Successful response', function(done) {
            // `key` is available here
        }
    });
})

Upvotes: 1

Related Questions