// src/posts/posts.e2e.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import * as request from 'supertest';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';
import { PostsModule } from './posts.module';
let mongod: MongoMemoryServer;
describe('PostsController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
mongod = await MongoMemoryServer.create();
const uri = mongod.getUri();
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(uri),
PostsModule,
],
}).compile();
app = moduleFixture.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
await app.init();
});
afterAll(async () => {
await app.close();
await mongoose.disconnect();
await mongod.stop();
});
afterEach(async () => {
// Clean slate between tests
const collections = mongoose.connection.collections;
for (const key in collections) {
await collections[key].deleteMany({});
}
});
describe('POST /posts', () => {
it('creates a post and returns 201', async () => {
const res = await request(app.getHttpServer())
.post('/posts')
.send({ title: 'My First Post', content: 'Hello world.' })
.expect(201);
expect(res.body).toMatchObject({
title: 'My First Post',
content: 'Hello world.',
});
expect(res.body._id).toBeDefined();
});
it('returns 400 when title is missing', async () => {
await request(app.getHttpServer())
.post('/posts')
.send({ content: 'No title here.' })
.expect(400);
});
it('returns 400 when title is too short', async () => {
await request(app.getHttpServer())
.post('/posts')
.send({ title: 'Hi', content: 'Too short.' })
.expect(400);
});
it('returns 409 when title already exists', async () => {
const body = { title: 'Duplicate Title', content: 'First one.' };
await request(app.getHttpServer()).post('/posts').send(body).expect(201);
await request(app.getHttpServer())
.post('/posts')
.send({ title: 'Duplicate Title', content: 'Second one.' })
.expect(409);
});
});
});