Skip to content

Commit

Permalink
Merge pull request #95 from shammy642/fix_pokemon_api_not_found
Browse files Browse the repository at this point in the history
added minPokemon and retry logic
  • Loading branch information
JHLincoln authored Oct 24, 2024
2 parents 77f9a04 + d32882a commit 8033eea
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
16 changes: 11 additions & 5 deletions api/numberGame/Pokemon.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
26 changes: 25 additions & 1 deletion api/tests/numberGame/pokemon.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})

Expand All @@ -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();
});

})

0 comments on commit 8033eea

Please sign in to comment.