Skip to content

Commit

Permalink
added minPokemon and retry logic
Browse files Browse the repository at this point in the history
  • Loading branch information
shammy642 committed Oct 24, 2024
1 parent 77f9a04 commit d32882a
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 d32882a

Please sign in to comment.