Skip to content

Commit

Permalink
tests setup
Browse files Browse the repository at this point in the history
  • Loading branch information
Victor committed Aug 4, 2022
1 parent fce1ce2 commit 0e5099c
Show file tree
Hide file tree
Showing 7 changed files with 3,533 additions and 706 deletions.
10 changes: 10 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/**/*.test.ts'],
verbose: true,
clearMocks: true,
resetMocks: true,
resetModules: true,
};
4,126 changes: 3,438 additions & 688 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"start": "set NODE_ENV=production&& npm run build && node dist/src/app.js",
"dev": "set NODE_ENV=development&& nodemon src/app.ts",
"build": "rimraf ./dist && tsc -p .",
"test": "jest"
"test": "jest --watch"
},
"author": "",
"license": "ISC",
Expand Down Expand Up @@ -37,14 +37,19 @@
"@types/config": "0.0.41",
"@types/connect-redis": "0.0.18",
"@types/express": "^4.17.13",
"@types/jest": "^28.1.6",
"@types/jsonwebtoken": "^8.5.8",
"@types/lodash": "^4.14.182",
"@types/mongoose": "^5.5.15",
"@types/morgan": "^1.9.3",
"@types/node": "^18.6.1",
"@types/supertest": "^2.0.12",
"@types/validator": "^13.7.4",
"jest": "^28.1.3",
"nodemon": "^2.0.19",
"rimraf": "^3.0.2",
"supertest": "^6.2.4",
"ts-jest": "^28.0.7",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
}
Expand Down
8 changes: 4 additions & 4 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ if (configuration().env === 'development') {
app.use(morgan('dev'));
}

// Limt requests from same IP to 500 per hour
const limiter = rateLimit({
max: 500,
windowMs: 60 * 60 * 1000,
Expand Down Expand Up @@ -72,7 +73,6 @@ app.use(
})
);

// app.use('/api/v1/auth', authRouter);
app.use('/api/v1/user', userRouter);
app.use('/api/v1/team', teamRouter);
app.use('/api/v1/fixture', fixtureRouter);
Expand All @@ -83,9 +83,9 @@ app.get('/', (req: Request, res: Response, next: NextFunction) => {

const port = configuration().port;

app.listen(port, () => {
app.listen(port, async () => {
logger.info(`Server running on port ${port}!`);
connect();
await connect();
});

app.all('*', (req, res, next) => {
Expand All @@ -94,4 +94,4 @@ app.all('*', (req, res, next) => {

app.use(errorHandler);

module.exports = app;
export default app;
2 changes: 1 addition & 1 deletion src/cache/cacheService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mongoose.Query.prototype.cache = function (options: any = {}) {
};

mongoose.Query.prototype.exec = async function () {
console.log('Im about to run a query');
logger.info('Serving data from cache');

if (!this.useCache) {
return exec.apply(this, arguments as any);
Expand Down
24 changes: 12 additions & 12 deletions src/user/services/authService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { omit } from 'lodash';
import logger from '../../logger';
import AppError from '../../utils/appError';
import { User } from '../interfaces';
Expand All @@ -6,19 +7,18 @@ import UserModel from '../models/userModel';
export const signup = async (
payload: User,
isAdmin?: boolean
): Promise<void> => {
try {
logger.info(`User signup with payload', ${JSON.stringify(payload)}`);
const role = isAdmin ? 'admin' : 'user';

if (role) {
payload.role = role;
}

await UserModel.create(payload);
} catch (error: any) {
throw new Error(error);
): Promise<User> => {
logger.info(`User signup with payload', ${JSON.stringify(payload)}`);
const role = isAdmin ? 'admin' : 'user';

if (role) {
payload.role = role;
}

const user = await UserModel.create(payload);

return user;
// return omit(user, 'password');
};

export const login = async (payload: {
Expand Down
62 changes: 62 additions & 0 deletions tests/user.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import mongoose from 'mongoose';
import request from 'supertest';

import app from '../src/app';
import * as authService from '../src/user/services/authService';

const userId = new mongoose.Types.ObjectId().toString();
const userPayload = {
_id: userId,
name: 'John Doe',
email: 'john@example.com',
role: 'user',
};

const userInput = {
name: 'John Doe',
email: 'john@examples.com',
password: '123456',
};

describe('User Test', () => {
// user registration

describe('user registration', () => {
describe('given the email and password are valid', () => {
it('should return a status code of 201 with message', async () => {
const createUserServiceMock = jest
.spyOn(authService, 'signup')
// @ts-ignore
.mockReturnValueOnce(userPayload);

const { statusCode, body } = await request(app)
.post('/api/v1/user/signup')
.send(userInput);

expect(statusCode).toBe(201);
expect(body.message).toEqual('User signup successful');
// expect(createUserServiceMock).toHaveBeenCalledWith(userInput);
});
});

describe('given the user service throws an error', () => {
it('should handle the error on signup', async () => {
const createUserServiceMock = jest
.spyOn(authService, 'signup')
// @ts-ignore
.mockReturnValueOnce(userPayload);

const { statusCode, body } = await request(app).post(
'/api/v1/user/signup'
);

expect(statusCode).toBe(201);
// expect(body.message).toEqual('User signup successful');
});
});
});
// the email and password gets validation
// verify that the handler handles any errors

// Create a user session
});

0 comments on commit 0e5099c

Please sign in to comment.