Search code examples
javascriptobjectprototype

Reference Error, Magic is not defined. But it is defined in the test parameters?


I'm working on this kata: https://www.codewars.com/kata/magic-the-gathering-number-3-spell-stack/train/javascript.

It throws this error on running sample tests:

ReferenceError: Magic is not defined
    at /home/codewarrior/index.js:7:1
    at Object.handleError
        <anonymous>

I've looked into how prototypes work and my code seems to be correct.

This is my code so far:

// Create the Magic object with a spellStack method
// Happy Casting!
Magic.prototype.spellStack = (card) => {
  console.log(card);
}

and the test parameters are this:

  Test.describe("It should add and remove spells on the stack", function() {
  let spells = [{'name':'Lightning Bolt', 'type': 'instant'}, {'name': 'Giant Growth', 'type': 'instant'},
                {'name':'Time Walk', 'type': 'sorcery'}, {'name': 'Ponder', 'type': 'sorcery'}]; 
  var myMagic = new Magic();

  Test.assertSimilar(myMagic.spellStack(spells[2]), 1);
  Test.assertSimilar(myMagic.spellStack(spells[0]), 2);
  Test.assertSimilar(myMagic.spellStack(spells[0]), 3);
  Test.assertSimilar(myMagic.spellStack(spells[1]), 4);
  Test.assertSimilar(myMagic.spellStack(), spells[1]);
  Test.assertSimilar(myMagic.spellStack(), spells[0]);
  Test.assertSimilar(myMagic.spellStack(), spells[0]);

  Test.it("Should throw an error if trying to add a sorcery to a stack with spells:", function() {
    Test.expectError(()=>myMagic.spellStack(spells[3]));
    Test.expectError(()=>myMagic.spellStack(spells[2]));
  });

  Test.it("Should throw an error if trying to retrieve a spell when the stack is empty:", function() {
    Test.assertSimilar(myMagic.spellStack(), spells[2], "Removing the last spell from the stack");
    Test.expectError(()=>myMagic.spellStack());
  });
});

At the very least it should give an error but also console out the functions input.


Solution

  • On this line

    Magic.prototype.spellStack = (card) => {
    

    You're setting a property on the prototype, but where is Magic defined? Magic doesn't exist yet.

    You need to define it first

    function Magic() {}
    Magic.prototype.spellStack = (card) => {
        console.log(card);
    }