Skip to content

Instantly share code, notes, and snippets.

@pepeloper
Created January 13, 2025 16:41
Show Gist options
  • Save pepeloper/98cec1440622b63fa557dec90678ea93 to your computer and use it in GitHub Desktop.
Save pepeloper/98cec1440622b63fa557dec90678ea93 to your computer and use it in GitHub Desktop.
API Testing con express
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