Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added minPokemon and retry logic #95

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});

})