From d32882af7146b46de8d35d5ec9abc584326272b7 Mon Sep 17 00:00:00 2001 From: Sam Hoile Date: Thu, 24 Oct 2024 10:55:59 +0100 Subject: [PATCH] added minPokemon and retry logic --- api/numberGame/Pokemon.js | 16 +++++++++++----- api/tests/numberGame/pokemon.test.js | 26 +++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/api/numberGame/Pokemon.js b/api/numberGame/Pokemon.js index cba1a19..168e2e7 100644 --- a/api/numberGame/Pokemon.js +++ b/api/numberGame/Pokemon.js @@ -1,14 +1,20 @@ class Pokemon { constructor() { + this._minPokemon = 1 this._maxPokemon = 1025; } async getRandom() { - const id = Math.floor(Math.random() * this._maxPokemon); - const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`) - const pokemon = await response.json() - return this._extractInfo(pokemon) - + const id = Math.floor(Math.random() * (this._maxPokemon - this._minPokemon + 1)) + this._minPokemon; + + try { + const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`) + const pokemon = await response.json() + return this._extractInfo(pokemon) + } catch(error) { + console.log("Error fetching pokemon, re-fetching!", error) + return this.getRandom() + } } _extractInfo(pokemon) { diff --git a/api/tests/numberGame/pokemon.test.js b/api/tests/numberGame/pokemon.test.js index 51f7777..ffa18f2 100644 --- a/api/tests/numberGame/pokemon.test.js +++ b/api/tests/numberGame/pokemon.test.js @@ -4,8 +4,9 @@ const fetchMock = require("jest-fetch-mock") describe('pokemon', () => { - test('initiates with _maxPokemon size of 1118', () => { + test('initiates with _minPokemon size of 1 and _maxPokemon size of 1025', () => { const pokemon = new Pokemon() + expect(pokemon._minPokemon).toBe(1) expect(pokemon._maxPokemon).toBe(1025) }) @@ -28,4 +29,27 @@ describe('pokemon', () => { fetchMock.resetMocks(); }) + test('getRandom retrieves an error and reruns getRandom until it gets a valid response', async () => { + fetchMock.enableMocks(); + const pokemon = new Pokemon(); + + fetchMock.mockRejectOnce(new Error("Network Error")); + fetchMock.mockResponseOnce(JSON.stringify({ + name: "sam", + sprites: { front_default: "http://mocksite.com" }, + weight: 75 + })); + + const result = await pokemon.getRandom(); + + expect(result).toEqual({ + name: "sam", + pictureURL: "http://mocksite.com", + weight: 75 + }); + + // Reset fetch mocks to clean up + fetchMock.resetMocks(); + }); + }) \ No newline at end of file