Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

377
Views
Establezca un token de autenticación en un encabezado de solicitud cuando use supertest con jest y express

Estoy tratando de probar las rutas en mi aplicación express que están protegidas por un middleware jwt. Intenté simular una solicitud para obtener el token jwt en una llamada beforeAll :

 let token = ""; beforeAll((done) => { supertest(app) .get("/authentication/test") .end((err, response) => { console.log(response.body); // "fewiu3438y..." (successfully got token) token = response.body.token; // Tried to update token variable with jwt token done(); }); }); console.log(token); // "" (I haven't updated the token variable)

Entonces, cuando intento ejecutar pruebas posteriores, no tengo un token de autenticación válido para usar en los encabezados:

 describe("Simple post test using auth", () => { test.only("should respond with a 200 status code", async () => { console.log({ POSTTest:token }); // "" still not set, so test will fail. const response = await supertest(app).post("/tests/simple").send(); expect(response.statusCode).toBe(200); }); });

¿Hay alguna forma de actualizar una variable o establecer todos los encabezados usando beforeAll ? ¿O hay un método mejor que no conozco?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Intente usar una función async como una devolución de llamada beforeAll :

 let token = ''; beforeAll(async () => { const response = await supertest(app).get('/authentication/test'); token = response.body.token; });

Luego, use el método set para pasar el token en la prueba:

 describe('Simple post test using auth', () => { test.only('should respond with a 200 status code', async () => { const response = await supertest(app) .post('/tests/simple') .set('Authorization', `Bearer ${token}`); expect(response.statusCode).toBe(200); }); });
about 4 years ago · Juan Pablo Isaza Report

0

estoy haciendo esto

 import * as request from 'supertest'; describe('Simple post test using auth', () => { test.only('should respond with a 200 status code', async () => { const res = await request(app.getHttpServer()) .post('/tests/simple') .send(payload) .set('Authorization', `Bearer ${token}`); expect(res.statusCode).toBe(200); }); });

También tengo una sugerencia de que se burle de su solicitud de autenticación. Aquí hay una pregunta similar para eso si está utilizando jest Solicitud de autenticación simulada -Jest

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!