I am trying to test my code with jasmine only. I have my route separated from the controller as seen below. The endpoints call model's functions which hit the database. I want to avoid hitting the database during testing. So, I was thinking of a way to mock the model's functions that the endpoints depend on but I don't know how to do so. Also, I don't know if there is a better way to test my endpoints without hitting the database.
jasmine test: UserController.spec.ts
/* eslint-disable no-undef */
import Request from 'request';
import { server } from '../../src/server';
import * as User from '../../src/api/models/User';
const urlAddress = 'http://localhost:3000';
describe('Server', () => {
afterAll(() => {
server.close();
});
describe('GET all users /', () => {
const data = {};
beforeAll((done) => {
Request.get(`${urlAddress}/users`, (_error, response, body) => {
data.status = response.statusCode;
data.body = body;
done();
});
});
it('Status 200', () => {
expect(data.status).toBe(200);
});
});
});
controller: UserController.ts
import { Router } from 'express';
import * as User from '../models/User';
export const UserController: Router = Router();
UserController.get('/', User.getUsers);
model: User.ts
import { Response, Request, NextFunction } from 'express';
import bcrypt from 'bcrypt';
import { pool, parseError } from '../db';
// define table
const table: string = 'users';
// set error message
// pool.on('error', (err, client) => `Error, ${err}, occured on ${client}`);
// select all users
const getUsers = (req: Request, res: Response, next: NextFunction) => {
pool.query(`SELECT * FROM ${table};`, (error, results) => {
if (error) {
parseError(error);
next(error);
} else {
res.status(200).json(results.rows);
}
});
};
router: routes.ts
import { Application, Router } from 'express';
import { UserController } from './controllers/UserController';
const _routes: [string, Router][] = [
['/users', UserController]
];
export const routes = (app: Application) => {
_routes.forEach((route) => {
const [url, controller] = route;
app.use(url, controller);
});
};
Aucun commentaire:
Enregistrer un commentaire