Created
January 13, 2025 16:41
-
-
Save pepeloper/98cec1440622b63fa557dec90678ea93 to your computer and use it in GitHub Desktop.
API Testing con express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import './test.config.js'; | |
import request from 'supertest'; | |
import { app } from '../main.js'; | |
import { connect, clearDatabase, disconnect } from './setup.js'; | |
import jwt from 'jsonwebtoken'; | |
import bcrypt from 'bcrypt'; | |
import User from '../users/user.model.js'; | |
const TEST_USER = { | |
username: 'testuser', | |
password: 'testpass123', | |
email: '[email protected]', | |
}; | |
const createTestUser = async () => { | |
const hashedPassword = await bcrypt.hash(TEST_USER.password, 10); | |
const user = new User({ | |
username: TEST_USER.username, | |
password: hashedPassword, | |
email: TEST_USER.email, | |
}); | |
await user.save(); | |
return user; | |
}; | |
const createTestToken = (email) => jwt.sign({ email: email }, process.env.JWT_SECRET); | |
describe('Snippets API', () => { | |
let testUser; | |
beforeAll(async () => { | |
await connect(); | |
}); | |
beforeEach(async () => { | |
testUser = await createTestUser(); | |
}); | |
afterEach(async () => { | |
await clearDatabase(); | |
}); | |
afterAll(async () => { | |
await disconnect(); | |
}); | |
describe('GET /api/snippets', () => { | |
test('should return 401 without token', async () => { | |
const response = await request(app) | |
.get('/api/snippets'); | |
expect(response.status).toBe(401); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment