I have a simple console application with some tests. All I am testing is to check that the game starts with level 1. If the current level is 2 the next one should be 3 etc. The following code works fine but I wanted to move out the gameMapper function to its own file and import it within the Game.js.
Game.js
export default class Game {
constructor(level) {
this.level = level;
}
static start = () => new Game(1);
getNextLevel = () => gameMapper.find((g) => g.level === this.level).nextLevel;
}
const gameMapper = [
{ level: 1, nextLevel: new Game(2) },
{ level: 2, nextLevel: new Game(3) },
{ level: 3, nextLevel: new Game(4) },
];
sample.test.js
import Game from '../src/Game';
describe('Test Game levels', () => {
test('Game should start from level 1', () => {
const game = Game.start();
expect(game.level).toBe(1);
});
test('When game level is 2, the next level should be 3', () => {
const game = Game.start().getNextLevel().getNextLevel();
expect(game.level).toBe(3);
});
});
The above code works completely fine. I have tried the following solutions but they did not seem to work for me. If anyone knows any better solutions please do let me know.
TypeError: _Game.default is not a constructorinit function to the Game class which requires the level argument and initialises the Game class with that level. But I get another error as explained below.gameMapper.js file
import Game from './Game';
export const gameMapper = [
{ level: 1, nextLevel: Game.init(2) },
{ level: 2, nextLevel: Game.init(3) },
{ level: 3, nextLevel: Game.init(4) },
];
updated Game.js file
import { gameMapper } from './gameMapper';
export default class Game {
static init = (level) => new Game(level);
getNextLevel = () => gameMapper.find((g) => g.level === this.level).nextLevel;
}
When I do the above where I move out the gameMapper and import it into the Game.js file I get the following error in gameMapper.js.
TypeError: Cannot read properties of undefined (reading 'init') at { level: 1, nextLevel: Game.init(2) }
I am expecting that the tests should still pass when I move out the mapper.
Thank you all for your precious time :)