Reputation: 510
I want to test my Express, MongoDB, TypeScript REST-Api, but I am having difficulty with a line of code where supertest takes app
as parameter. The test fails and I get the 404 status code instead of 200.
const resVar = await supertest(app).get(`/`);
expect(resVar.statusCode).toBe(200);
However when I replace the parameter app with http://localhost:${EXPRESS_APP_PORT}/api/v1/users
the test passes and I get a 200 status code.
This is a small project and you can get & clone all the code on this Github repository.
Looking forward to your help.
server.ts
(server initialization location/file) ⬇
import express, {Application} from 'express';
import cors from 'cors';
import {deserializeUserFunc} from './middleware/deserializeUser';
import {routes} from './routes/index';
const initServer = () => {
const app: Application = express();
app.use(cors());
app.use(express.json());
app.use(deserializeUserFunc);
app.use('/api/v1/users', routes);
return app;
};
export {initServer}
index.ts
(connection to MonGODB & listening to port occurs here, but not for testing environment.) ⬇
import {initServer} from './server';
import {EXPRESS_APP_PORT, MONGO_DB_USERNAME, MONGO_DB_DATABASE} from './config';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const mongoDbPassword = process.env.MONGODB_PASSWORD;
import pinoLogger from './logger';
// connect to online mongoDB
mongoose.connect(`mongodb+srv://${MONGO_DB_USERNAME}:${mongoDbPassword}@emmethubclusterone.disfr.mongodb.net/${MONGO_DB_DATABASE}?retryWrites=true&w=majority` )
.then(() => {
pinoLogger.info(`Connected to ${MONGO_DB_DATABASE} database.`);
})
.catch((err) => {
pinoLogger.error(`${err} Error connecting to ${MONGO_DB_DATABASE} database!`);
process.exit(1);
})
const app = initServer();
app.listen(EXPRESS_APP_PORT, () => {
pinoLogger.info(`App server is listening at http://localhost:${EXPRESS_APP_PORT}`);
})
product.test.ts
(my file with the test that fails.) ⬇
import supertest from 'supertest';
import {initServer} from "../server" ;
import {MongoMemoryServer} from 'mongodb-memory-server';
import mongoose from 'mongoose';
const app = initServer();
describe('product', () => {
beforeAll( async() => {
const mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri())
})
afterAll(async() => {
await mongoose.disconnect();
await mongoose.connection.close();
})
describe('get product route', () => {
describe('given the product exists', () => {
it('should return a 200 and the product', async() => {
const resVar = await supertest(app).get(`/`);
expect(resVar.statusCode).toBe(200);
})
});
})
});
Upvotes: 1
Views: 2078
Reputation: 436
It might be because of the route you specified in product.test.ts
. In index.ts
you state app.use('/api/v1/users', routes);
but in product.test.ts
you target:
await supertest(app).get(`/`);
Try with
await supertest(app).get(`/api/v1/users`);
Upvotes: 1