1+ const request = require ( 'supertest' ) ;
2+ const express = require ( 'express' ) ;
3+ const axios = require ( 'axios' ) ;
4+ const publicationsRouter = require ( '../routes/publications' ) ;
5+
6+ // Mock the axios module
7+ jest . mock ( 'axios' ) ;
8+
9+ const app = express ( ) ;
10+ // Mount the router to a path
11+ app . use ( '/api/publications' , publicationsRouter ) ;
12+
13+ describe ( 'Backend API: /api/publications' , ( ) => {
14+
15+ afterEach ( ( ) => {
16+ // Clear all mocks after each test
17+ jest . clearAllMocks ( ) ;
18+ } ) ;
19+
20+ describe ( 'GET /api/publications/search' , ( ) => {
21+
22+ // Test for Async Logic Handling and Data Transformation
23+ it ( 'should return successfully with formatted data when OpenAlex API call succeeds' , async ( ) => {
24+ const mockApiResponse = {
25+ data : {
26+ results : [
27+ { id : 'W123' , display_name : 'Test Publication 1' , cited_by_count : 50 } ,
28+ { id : 'W456' , display_name : 'Test Publication 2' /* missing cited_by_count */ } ,
29+ ] ,
30+ meta : { count : 2 } ,
31+ } ,
32+ } ;
33+ axios . get . mockResolvedValue ( mockApiResponse ) ;
34+
35+ const response = await request ( app ) . get ( '/api/publications/search?filter=test' ) ;
36+
37+ expect ( response . status ) . toBe ( 200 ) ;
38+ expect ( response . body . results ) . toHaveLength ( 2 ) ;
39+ // Check that data transformation (adding citation_count) works correctly
40+ expect ( response . body . results [ 0 ] ) . toHaveProperty ( 'citation_count' , 50 ) ;
41+ expect ( response . body . results [ 1 ] ) . toHaveProperty ( 'citation_count' , 0 ) ; // Check for default value
42+ } ) ;
43+
44+ // Test for Error Handling Middleware
45+ it ( 'should return a 500 error when the OpenAlex API call fails' , async ( ) => {
46+ const errorMessage = 'Network Error' ;
47+ axios . get . mockRejectedValue ( { message : errorMessage } ) ;
48+
49+ const response = await request ( app ) . get ( '/api/publications/search?filter=test' ) ;
50+
51+ expect ( response . status ) . toBe ( 500 ) ;
52+ expect ( response . body ) . toEqual ( {
53+ error : 'Failed to fetch from OpenAlex API' ,
54+ details : errorMessage ,
55+ } ) ;
56+ } ) ;
57+ } ) ;
58+ } ) ;
0 commit comments