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.
It works for me.
index.js
:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/api/genres', (req, res) => {
console.log('api genres');
res.sendStatus(200);
});
const server = app.listen(port, () => console.log(`Listening on port ${port}`));
module.exports = server;
index.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);
});
});
});
Test results:
PASS apollo-graphql-tutorial src/stackoverflow/60321422/index.test.js
/api/genres
GET /
✓ should return all genres (289ms)
console.log src/stackoverflow/60321422/index.js:11
Listening on port 3000
console.log src/stackoverflow/60321422/index.js:7
api genres
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.693s, estimated 2s