Skip to content

Instantly share code, notes, and snippets.

@MatiasDelorenzi
Last active August 18, 2023 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatiasDelorenzi/47478a472ee09b106cd2c8000d1a1481 to your computer and use it in GitHub Desktop.
Save MatiasDelorenzi/47478a472ee09b106cd2c8000d1a1481 to your computer and use it in GitHub Desktop.
Testing with NodeJS
export function sum(a: number,b: number): number{
return a + b;
}
import { sum } from './myFunction.ts';
describe('Testing sum function', () => {
it('Should add two numbers correctly', () => {
// Arrange
const a: number = 4;
const b: number = 1;
//Act
const result = sum(a, b);
//Assert
expect(result).toBe(5);
})
})
import * as request from 'supertest';
import app from '../server.ts';
describe('User', () => {
describe('Create user endpoint', () => {
it('Should return 201 HTTP status code and new user id', async () => {
const response = await request(app)
.post('/api/user')
.send({
email: 'test@email.com',
password: 'supersecurepassword'
})
expect(response.statusCode).toEqual(201);
expect(response.body).toEqual('new-user-id')
})
it('Should return an error message if parameters are missing', async () => {
const response = await request(app)
.post('/api/user')
.send({});
expect(response.statusCode).toEqual(422);
expect(response.body).toEqual('You must enter a valid email and password.')
})
})
})
import { DatabaseUtils } from '../utils/database.ts';
import { CreateUserDto } from '../dtos/user.ts';
export default class UserService{
databaseUtils: DatabaseUtils;
constructor(){
this.databaseUtils = new DatabaseUtils();
}
public async createUser(
body: CreateUserDto
): Promise<string>{
if(!body.email || !body.password){
throw new Error('You must enter your email and password');
}
const newUserId = await this.databaseUtils.createUser(body);
return newUserId;
}
}
describe('User Service class', () => {
const userService = new UserService();
describe('createUser method', () => {
it('Should throw an error if email and password are not sent', async () => {
const bodySent = {};
await expect(userService.createUser(bodySent)).rejects.toThrowError(
new Error('You must enter your email and passowrd')
);
})
it('Should return a string if user is created', async () => {
//Arrange
const body: CreateUserDto = {
email = 'test@email.com',
password = 'supersecurepassword'
};
jest
.spyOn(userService.databaseUtils, 'createUser')
.mockResolvedValueOnce('created-user-id');
//Act
const serviceResponse = await userService.createUser(body);
//Assert
expect(serviceResponse).toEqual('created-user-id');
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment