I'm working on a sample ExpressJs application written with Typescript in which I tried to implement Jest. I have a service class which I want to test but it seems like Jest is looking at the wrong source codes when I run the actual test.
If you look at the stack trace of the error, it seems it is executing a lot more than it should. I'm only testing auth.service.ts
but it seems it is scanning a lot more. Below is my auth.service.ts
file.
import { generateUuid, isPasswordMatching, redisClient } from '../utils';
import { getUserService } from './user.service';
class AuthService {
private userService = getUserService();
async login(username: string, password: string): Promise<string | null> {
const user = await this.userService.getUserByUsername(username);
if (!user) return null;
if (!(await isPasswordMatching(password, user.password))) return null;
if (!user.token) {
user.token = generateUuid();
await user.save();
}
await redisClient.set(user.token, user.userId);
return user.token;
}
}
const authService = new AuthService();
export const getAuthService = (): AuthService => {
return authService;
};
And here is my test file which is what I'm trying to execute.
import { getAuthService } from '../../src/services/auth.service';
const authService = getAuthService();
test('auth service init', () => {
expect(authService).not.toBeNull();
});
Any idea on what could be wrong?
UPDATE: posting my auth.route.ts
file as well
import { Request, Response, Router } from 'express';
import { getAuthService } from '../services';
import { loginSchema, validateParams } from '../validators';
const authService = getAuthService();
export const authRoute = (router: Router) => {
router.post('/login', async (req: Request, res: Response) => {
const { data, error } = await validateParams(req.body, loginSchema);
if (error) {
res.status(400).send({ message: error });
return;
}
const token = await authService.login(data.username, data.password);
if (!token) {
res.status(400).send({ message: `Invalid credentials.` });
return;
}
res.status(200).send({ token });
});
};