I'm new to Node and Mocha and am having difficulty in understanding why Mocha is skipping over my 'before' hook code to create a Json Web Token in the following example:
//index.js
const createJWT = require('./lib/config/createJWT');
const expect = require('chai').expect;
before(async() => {
  const jwt = await createJWT() {
    return new Promise(
      function(resolve, reject) {
        resolve(jwt);
      }
    )
  }
  const person = createPerson(jwt);
}); //this is where the jwt is created, making it useless for createPerson
describe('My other tests', () => {
it('Customer sign up', async() => {
  const signUpText = await customerSignUp(page, frame);
  expect(signUpText).to.equal("You have signed up")
  });
 });
});The createJWT() method is as follows:
 //createJWT.js
module.exports = async() => {
  const options = {
    method: 'POST',
    url: 'https://my-website.auth.io/oauth/token',
    headers: {
      'content-type': 'application/json'
    },
    body: '{"client_id":"dew76dw7e65d7w65d7wde"}'
  };
    request(options, function (error, response, body) {
    try {
        console.log(body);
        jwt = body;
        return jwt = body;
    } catch
        (error) {
    }
  });
};When I debug, the setup code is skipped over. Is there something obvious I'm missing?
I am pretty sure you need to put the before hook in the same test block for it to be ran before it is processed. Ex :
before(async() => {
  const jwt = await createJWT();
});
describe('My other tests', () => {
  it('Customer sign up', async() => {
    const signUpText = await customerSignUp(page, frame);
    expect(signUpText).to.equal("You have signed up")
  });
});
Or :
describe('My other tests', () => {
  before(async() => {
    const jwt = await createJWT();
  });
  it('Customer sign up', async() => {
    const signUpText = await customerSignUp(page, frame);
    expect(signUpText).to.equal("You have signed up")
  });
});
Furthermore, your createJwt method does not return a Promise, which prevents the await from working. You need to do something like this :
module.exports = async() => {
  const options = {
    method: 'POST',
    url: 'https://my-website.auth.io/oauth/token',
    headers: {
      'content-type': 'application/json'
    },
    body: '{"client_id":"dew76dw7e65d7w65d7wde"}'
  };
  return new Promise((resolve, reject) => request(options, function (error, response, body) {
    if(error) {
      reject(error);
    }
    resolve(body);
  }));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With