0

I working a test that requieres a token in order to run. This token is required to be passed to the compare function. But i'm not understanding on how to wait for the token in order to procede to execute the test. I'm new JS so apologies. Here is the code of my test:

  describe('Offline Comparison', function () {
  token = getToken('appName');
  console.log('Token' + token);
  files.forEach(function (file) {
    it('Comparando file ' + file, function (done) {
      this.timeout(15000);
      const id = file.split('./screenshots/')[1];
      compare(file, id, token, function (response) {
        console.log(JSON.stringify(response, null, 4));
        expect(response.TestPassed).to.be.true;
        done();
      });
    });
  });
});

function getToken(applicationName, callback) {
  request.post('http://localhost:8081/token',
    {
      json: {
        application_name: applicationName
      }
    },
    (error, response, body) => {
      console.log('Token: ' + body.Token);
      return callback(body.Token)
    });
}
elcharrua
  • 1,582
  • 6
  • 30
  • 50
  • `Describe` is not part of Javascript, it is a function defined in the library you used (namely Jasmine) – Tushar Gupta Jul 26 '18 at 01:17
  • I think you should put the `file.forEach` function into the callback so as to ensure the existence of response for running comparison. Or it will run asynchronously and thus may lose your token. – MT-FreeHK Jul 26 '18 at 01:29

2 Answers2

0

Your getToken() function is asynchronous and takes a callback. You can't just call it and expect and answer, you need to pass it a callback function that it will call back with the token as an argument. You'll need something like this to get the token:

describe('Offline Comparison', function () {
  getToken('appName', function(token){   // <- pass getToken a callback
      console.log('Token' + token);      // <- token should now be available
      files.forEach(function (file) {
        it('Comparando file ' + file, function (done) {
          this.timeout(15000);
          const id = file.split('./screenshots/')[1];
          compare(file, id, token, function (response) {
              console.log(JSON.stringify(response, null, 4));
              expect(response.TestPassed).to.be.true;
              done();
          });
        });
      });
    }); 
});
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Move the getToken execution out of the describe function and pass the describe function as the callback to the getToken function

getToken('appName', describe);
describe('Offline Comparison', function (token) {
  ...
});

function getToken(applicationName, callback) {
   request.post('http://localhost:8081/token',
  {
    json: {
      application_name: applicationName
    }
  },
  (error, response, body) => {
    console.log('Token: ' + body.Token);
    return callback(body.Token)
  });
}