Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
Mocha test fails before async function in beforeEach() completes

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();
  });
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda