Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authentication test #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: [
"/node_modules/"
"/node_modules/",
"./spec/test-setup.ts",
],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
testMatch: [
"**/spec/**/*.ts?(x)",
"**/?(*.)+(spec|test).ts?(x)"
]
};
};
50 changes: 50 additions & 0 deletions spec/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const mongoose = require("mongoose");
mongoose.set("useCreateIndex", true);
mongoose.promise = global.Promise;
import app from '../src/Server';
import { users } from './user.spec';
const supertest = require('supertest');
const request = supertest(app);

jest.setTimeout(15000);

async function dropAllCollections() {
const collections = Object.keys(mongoose.connection.collections);
for (const collectionName of collections) {
const collection = mongoose.connection.collections[collectionName];
try {
await collection.drop();
} catch (error) {
// Sometimes this error happens, but you can safely ignore it
if (error.message === "ns not found") return;
// This error occurs when you use it.todo. You can
// safely ignore this error too
if (error.message.includes("a background operation is currently running"))
return;
console.log(error.message);
}
}
}

module.exports = {
setupDB(databaseName: string) {
// Connect to Mongoose
beforeAll(async () => {
const url = `mongodb://127.0.0.1/${databaseName}`;
await mongoose.connect(url, { useNewUrlParser: true });

const res = await request.post('/api/users/')
.send({
name: users[0].name,
email: users[0].email,
password: users[0].password
});
});

// Disconnect Mongoose
afterAll(async () => {
await dropAllCollections();
await mongoose.connection.close();
});
}
};
172 changes: 172 additions & 0 deletions spec/user.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import app from '../src/Server';
const supertest = require('supertest');
const request = supertest(app);
import mongoose from "mongoose"

import User from '../src/entities/User/User.schema';
import IUser from '../src/entities/User/User.interface';
const { setupDB } = require("./test-setup");

setupDB('endpoint-testing');

export const users: IUser[] = [
{
_id: new mongoose.Types.ObjectId(),
name: 'test1',
email: 'testowymail748test1638@gmail.com',
password: 'test1'
}
];

describe("POST / ", () => {

it('Should save user to database', async done => {
const res = await request.post('/api/users/')
.send({
name: "test4",
email: 'testowymail7486test439@gmail.com',
password: "test4"
});

// Ensures response contains name and email
expect(res.body.name).toBeTruthy();
expect(res.body.email).toBeTruthy();
// Ensures response status
expect(res.statusCode).toBe(201);

// Searches the user in the database
const user = await User.findOne({ email: users[0].email });
if(user) {
expect(user.name).toBeTruthy();
expect(user.email).toBeTruthy();
}

done();
});

it('Should throw error - Email already registered', async done => {
const res = await request.post('/api/users/')
.send({
name: "test5",
email: users[0].email,
password: "test5"
});

expect(res.statusCode).toBe(400);
expect(res.text).toBe("Email already registered");

// Searches the user in the database
const user = await User.findOne({ name: "test5" });
expect(user).toBe(null);

done();
});

it('Should throw error - Name already registered', async done => {
const res = await request.post('/api/users/')
.send({
name: "test1",
email: "testowymail7486test539@gmail.com",
password: "test1"
});

expect(res.statusCode).toBe(400);
expect(res.text).toBe("Name already registered");

// Searches the user in the database
const user = await User.findOne({ email: "testowymail7486test539@gmail.com" });
expect(user).toBe(null);

done();
});

});

describe("GET /", () => {
it('Should get users from db', async done => {

let res = await request.get("/api/users/");

expect(res.status).toBe(200);
expect(res.body).toBeDefined;
expect(res.body[0].name).toBeTruthy;

done();
});

it('Should get one user from db', async done => {

const user = await User.findOne({ name: users[0].name });
if(user) {
const res = await request.get(`/api/users/${user._id}`);

expect(res.status).toBe(200);
expect(res.body).toBeDefined;
expect(res.body.name).toBeTruthy();
expect(res.body.email).toBeTruthy();
}

done();
});

it('Should throw error - user not found', async done => {

const res = await request.get(`/api/users/6017daf7bbbbbbbbbbbbbbbb`);

expect(res.status).toBe(404);
expect(res.body).toBeNull;
expect(res.text).toBe("User not found");

done();
});

it('Should get users books from db', async done => {
const user = await User.findOne({ name: users[0].name });
if(user) {
const res = await request.get(`/api/users/${user._id}/books`);

expect(res.status).toBe(200);
expect(res.body).toBeDefined;
expect(res.body).toEqual([]); // returns empty array cuz no books
//expect(res.body[0].name).toBeTruthy; // if some book(s)
}

done();
});

})

describe("GET /me", () => {

it("returns logged user info", async () => {

let auth = {
token: ''
};
let res = await request.post('/api/auth/')
.send({
email: users[0].email,
password: users[0].password
});

expect(res.body.token).toBeTruthy;
auth.token = res.body.token;

res = await request.get("/api/me/")
.set("Authorization", 'Bearer ' + auth.token);

expect(res.status).toBe(200);
expect(res.body._id).toBeTruthy;
expect(res.body.name).toBeTruthy;
expect(res.body.email).toBeTruthy;
});

it("returns error: no token", async () => {

const res = await request.get("/api/me/")

expect(res.status).toBe(400);
expect(res.body.error).toBeTruthy;
expect(res.body.error).toBe("No authorization token was found");
});
});
4 changes: 2 additions & 2 deletions src/entities/Basket/Basket.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import validateBasketReq from './Basket.validation';
import Basket from './Basket.schema';
import User from '../User/User.schema'
import Book from '../Book/Book.schema'
import IUser from '@entities/User/User.interface';
import IBook from '@entities/Book/Book.interface';
import IUser from '../User/User.interface';
import IBook from '../Book/Book.interface';

const { BAD_REQUEST, FORBIDDEN, CREATED, OK } = StatusCodes;

Expand Down
9 changes: 5 additions & 4 deletions src/entities/Book/Book.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { Request, Response } from 'express';
import validateBookReq from './Book.validation';
import Book from '../../entities/Book/Book.schema';
import User from '../../entities/User/User.schema';
import { NOTFOUND } from 'node:dns';

const { BAD_REQUEST, CREATED, OK } = StatusCodes;
const { BAD_REQUEST, CREATED, OK, NOT_FOUND } = StatusCodes;


export const getBooks = async (req: Request, res: Response) => {
Expand Down Expand Up @@ -41,7 +42,7 @@ export const getBookById = async (req: Request, res: Response) => {
const book = await Book
.findById(req.params.id)
.populate('ownerId', ['location', 'name']);
if (!book) return res.status(BAD_REQUEST).send('Book not found');
if (!book) return res.status(NOT_FOUND).send('Book not found');
return res.status(OK).json(book);
} catch (error) {
return res.status(BAD_REQUEST).send(error.message);
Expand Down Expand Up @@ -71,7 +72,7 @@ export const updateBook = async (req: Request, res: Response) => {
{ $set: req.body },
{ new: true })
.populate('ownerId', 'name')
if (!book) return res.status(BAD_REQUEST).send('There is no book to be updated')
if (!book) return res.status(NOT_FOUND).send('There is no book to be updated')
return res.status(OK).json(book);
} catch (error) {
return res.status(BAD_REQUEST).send(error.message);
Expand All @@ -82,7 +83,7 @@ export const deleteBook = async (req: Request, res: Response) => {
try {
const deletedBook = await Book
.findOneAndRemove({ _id: req.params.id, ownerId: req.user });
if (!deletedBook) return res.send(BAD_REQUEST).send('There is no book to be updated')
if (!deletedBook) return res.status(NOT_FOUND).send('There is no book to be deleted')
return res.status(OK).json(deletedBook);
} catch (error) {
return res.status(BAD_REQUEST).send(error.message);
Expand Down
4 changes: 2 additions & 2 deletions src/entities/Me/Me.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import StatusCodes from 'http-status-codes';
import { Request, Response } from 'express';
import User from '../User/User.schema';
import Book from '../../entities/Book/Book.schema';
import Basket from '@entities/Basket/Basket.schema';
import Book from '../Book/Book.schema';
import Basket from '../Basket/Basket.schema';
import Conversation from "../Conversation/Conversation.schema";

const { BAD_REQUEST, OK, NOT_FOUND } = StatusCodes;
Expand Down
4 changes: 2 additions & 2 deletions src/entities/User/User.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import _ from 'lodash';
import Book from '../../entities/Book/Book.schema';
import { sendMail } from '../../shared/email';

const { BAD_REQUEST, OK, CREATED } = StatusCodes;
const { BAD_REQUEST, OK, CREATED, NOT_FOUND } = StatusCodes;


export const getUsers = async (req: Request, res: Response) => {
Expand All @@ -19,7 +19,7 @@ export const getUsers = async (req: Request, res: Response) => {
export const getUserById = async (req: Request, res: Response) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(BAD_REQUEST).send('User not found');
if (!user) return res.status(NOT_FOUND).send('User not found');
return res.status(OK).json(user);
} catch (error) {
return res.status(BAD_REQUEST).send(error.message);
Expand Down
2 changes: 1 addition & 1 deletion src/routes/basket.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express';
import checkToken from 'express-jwt';
import { getBasketById, addBasket } from '@entities/Basket/Basket.controller';
import { getBasketById, addBasket } from '../entities/Basket/Basket.controller';

const router = Router();

Expand Down
2 changes: 1 addition & 1 deletion src/routes/conversation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Router } from 'express';
import checkToken from 'express-jwt';
import { sendMessage, updateReadMessagesByInterlocutorsId } from '@entities/Message/Message.controller';
import { sendMessage, updateReadMessagesByInterlocutorsId } from '../entities/Message/Message.controller';

const router = Router();

Expand Down