Anri
Anri

Reputation: 3

Jasmine + Async functions

Here is my code:

'use strict';

var unitID = 0;

var getById = function(generalOptions, specificOptions) {


describe('API tests for: ' + specificOptions.name, function() {
var url = generalOptions.baseUrl + specificOptions.route;



// GET all items
it('= = = GET ALL test for ' + specificOptions.name + ' return status 
code 200',  function(done) {
  generalOptions.request.get({
    url: url
  }, function(error, response, body) {
    expect(response.statusCode).toBe(200);
    expect(JSON.parse(body)).not.toBeFalsy();

    if (specificOptions.route == '/devices/') {
      var bodyJS = JSON.parse(body);
      unitID = bodyJS.devices[0].id;
    } else {
     unitID = '';
    }
    console.log('Result 1 - ' + unitID);
    done();

  });
});


//GET by ID
it('= = = GET by ID test for ' + specificOptions.name + ' return status code 200', function(done) {
  console.log('Result 2 - ' + unitID);
  generalOptions.request.get({
    url: url + unitID
  }, function(error, response, body) {
    expect(response.statusCode).toBe(200);
    expect(JSON.parse(body)).not.toBeFalsy();
    done();
      });
    });
  })
};

module.exports = getById;

I need to wait, while unitID will be updated with first GET request and then use in in the next request.

The problem is, that it works asynchronously and unitID in the second request stay 0.

Can show how to implement solution with async/await or Promises? Thanks!

For debugging reason I do console.log. For now it print:
Result 2 - 0
Result 1 - 59dffdgfdgfg45545g

Upvotes: 0

Views: 139

Answers (1)

khawar jamil
khawar jamil

Reputation: 166

You should not write test in such fashion where output of one test goes into other.Each "it" should be independent.

Instead you should make call twice(nested call) to achieve the value of unitID or ideally you should mock the service to return the data that is expected by the "it".

Upvotes: 1

Related Questions