Skip to content

added tests for validation and server error #1

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

Merged
merged 6 commits into from
Dec 10, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import app from '../../index.js';
import request from 'supertest';
import { Request, Response } from 'express';
import { fetchFromNewsAPI } from '../../utils.js';
import newsController from '../../modules/News/controller.js';

jest.mock('../../utils.ts');
jest.mock('../../middleware/auth.ts', () =>
jest.fn((req, res, next) => next()),
);

const mockFetchFromNewsAPI = fetchFromNewsAPI as jest.Mock;

Expand Down Expand Up @@ -70,4 +75,43 @@ describe('getTopHeadlines controller', () => {
},
]);
});

it('should return an empty array if no articles are found', async () => {
const mockArticles = { articles: [] };

mockFetchFromNewsAPI.mockResolvedValue(mockArticles);

await newsController.getTopHeadlines(req, res);

expect(mockFetchFromNewsAPI).toHaveBeenCalledWith('/top-headlines', {
country: 'de',
category: 'business',
pageSize: '10',
});

expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith([]);
});

it('should return 500 status code if the fetchFromNewsAPI throws an error', async () => {
mockFetchFromNewsAPI.mockRejectedValue(new Error());

await newsController.getTopHeadlines(req, res);

expect(res.status).toHaveBeenCalledWith(500);
expect(res.send).toHaveBeenCalledWith({
message: 'Error in getting the top headlines',
error: Error(),
});
});

it('should return 400 for invalid query parameters', async () => {
const res = await request(app).get('/api/news/headlines').query({
country: 'bra',
});
expect(res.status).toBe(400);
expect(res.body.error).toContain(
'"country" length must be 2 characters long',
);
});
});
Loading