0

what kind of async madness have I got myself into?

Test fails, then it logs the access token!

import assert from "assert";
import "dotenv/config";
import { expect } from "chai";
var unirest = require("unirest");

describe("some tests", function () {
  let accessToken: string | undefined;

  beforeEach(function () {
    const email = process.env.EMAIL;
    const password = process.env.PASSWORD;
    const login = async function () {
      const req = await unirest(
        "POST",
        `${process.env.API_BASE_URL}/auth/local/login`
      )
        .headers({
          "Content-Type": "application/json",
        })
        .send(JSON.stringify({ email, password }))
        .end(function (res: any) {
          if (res.error) throw new Error(res.error);
          accessToken = JSON.parse(res.raw_body).access_token;
          console.log(accessToken); // this logs after the test fails? why?
        });
    };
    login();
  });
  it("should be able to login and get an access token", async function () {
    expect(accessToken).to.not.be.undefined;
  });
});

The error is

    AssertionError: expected undefined not to be undefined

I've also tried returning login() but its still logs after it fails

  beforeEach(function () {
    const email = process.env.EMAIL;
    const password = process.env.PASSWORD;
    const login = async function () {
      const req = await unirest(
        "POST",
        `${process.env.API_BASE_URL}/auth/local/login`
      )
        .headers({
          "Content-Type": "application/json",
        })
        .send(JSON.stringify({ email, password }))
        .end(function (res: any) {
          if (res.error) throw new Error(res.error);
          accessToken = JSON.parse(res.raw_body).access_token;
          console.log(accessToken); // this logs after the test fails? why?
        });
    };
    return login();
  });
Bill
  • 4,614
  • 13
  • 77
  • 132
  • Check https://jestjs.io/docs/setup-teardown#repeating-setup - try `return login();` from beforeEach function. – James May 24 '22 at 20:25
  • Apologies, you are using Mocha not Jest. https://stackoverflow.com/questions/24723374/async-function-in-mocha-before-is-alway-finished-before-it-spec - still try return login() – James May 24 '22 at 20:26
  • 1
    Does this answer your question? [Async function in mocha before() is alway finished before it() spec?](https://stackoverflow.com/questions/24723374/async-function-in-mocha-before-is-alway-finished-before-it-spec) – hoangdv May 25 '22 at 01:17
  • @hoangdv yes it did but having to wrap every test in a promise is a bit annoying – Bill May 25 '22 at 09:22

0 Answers0