diff --git a/__tests__/apiController.test.js b/__tests__/apiController.test.js new file mode 100644 index 0000000..1acb878 --- /dev/null +++ b/__tests__/apiController.test.js @@ -0,0 +1,54 @@ +const apiController = require('../server/controllers/apiController.js'); +const fetch = require('node-fetch'); + +jest.mock('node-fetch'); + +describe('apiController.newYorkTimes', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should fetch top-selling books data from the New York Times API and store it in res.locals.bestSellers', async () => { + const mockResponse = { + json: jest.fn().mockResolvedValueOnce({ + results: { + books: [ + { title: 'Mock Book 1', author: 'Mock Author 1', rank: 1 }, + { title: 'Mock Book 2', author: 'Mock Author 2', rank: 2 } + ] + } + }) + }; + + fetch.mockResolvedValueOnce(mockResponse); + + const req = {}; + const res = {}; + const next = jest.fn(); + + await apiController.newYorkTimes(req, res, next); + + expect(fetch).toHaveBeenCalledWith('INSERT THE API HERE'); + expect(mockResponse.json).toHaveBeenCalled(); + expect(res.locals.bestSellers).toEqual([ + { title: 'Mock Book 1', author: 'Mock Author 1', rank: 1 }, + { title: 'Mock Book 2', author: 'Mock Author 2', rank: 2 } + ]); + expect(next).toHaveBeenCalled(); + }); + + it('should handle error if there is an issue fetching top-selling books data from the New York Times API', async () => { + const mockError = new Error('Mocked error in fetch'); + fetch.mockRejectedValueOnce(mockError); + + const req = {}; + const res = {}; + const next = jest.fn(); + + await apiController.newYorkTimes(req, res, next); + + expect(fetch).toHaveBeenCalledWith('INSERT THE API HERE'); + expect(res.locals.bestSellers).toBeUndefined(); + expect(next).toHaveBeenCalledWith(mockError); + }); +}); \ No newline at end of file diff --git a/server/controllers/apiController.js b/server/controllers/apiController.js index 90f7261..fac863e 100644 --- a/server/controllers/apiController.js +++ b/server/controllers/apiController.js @@ -33,6 +33,10 @@ apiController.checkApi = async (req, res, next) => { } } +apiController.newYorkTimes = async (req, res, next) => { + +} + // apiController.addToGlobalLibrary = async (req, res, next) => { // try { // const olWorkNumber = req.body;