jeudi 20 février 2020

React Jest issue when exporting server for integration testing

Quite simple situation, I am trying to import app.listen(port) for testing purposes. The tests will fail (fail reasons: app.address is not a function & server.close is not a function). Actually the server variable returns an empty object so the import is not done properly and that is the reason why the test cases are failing...

genres.test.js

const request = require("supertest");

let server;

describe("/api/genres", () => {
  beforeEach(() => {
    server = require("../../index");
  });
  afterEach(() => {
    server.close();
  });

  describe("GET /", () => {
    it("should return all genres", async () => {
      const res = await request(server).get("/api/genres");
      expect(res.status).toBe(200);
    });
  });
});

index.js

const express = require("express");
const app = express();

const port = process.env.PORT || 3000;
    const server = app.listen(port, () => console.log(`Listening on port ${port}`));

    module.exports = server;

Am I missing something about the import? Let me know if you need the more code lines/parts (note that the index.js I provided is not complete) or if you need the full error message.

I know this question has been already asked several times but in most cases, the solution is just to import app.listen instead of app, which I already did. I also tried to use export default instead of module.exports.

Aucun commentaire:

Enregistrer un commentaire