Home > Software design >  afterEach Jest not clearing my totalScore
afterEach Jest not clearing my totalScore

Time:11-10

For some reason I am getting:

1st test passes: "Love all"

2nd test fails: Expected: "Fifteen love" Received: "Fifteen loveLove all"

As I understand it, I need to be using afterEach to tear down the original configuration. I have tried this but it doesn't seem to 'wipe' the totalScore.

Thanks for your help!

Test file:

  const Tennis = require("../src/index");

describe("Tennis game", () => {
  let tennis;
  beforeEach(() => {
    tennis = new Tennis();
  });

  afterEach(() => {
    tennis.resetGame();
  });

  const scoreShouldBe = (expected) => {
    tennis.getScore();
    expect(tennis.totalScore).toBe(expected);
  };

  test("Love all", () => {
    scoreShouldBe("Love all");
  });

  test("Fifteen love", () => {
    tennis.firstPlayerScore();
    scoreShouldBe("Fifteen love");
  });
});

Index.js file:

    class Tennis {
  constructor() {
    this.firstPlayerScoreTimes = 0;
    this.totalScore = "";
  }
  getScore() {
    if (this.firstPlayerScoreTimes === 1) {
      this.totalScore  = "Fifteen love";
    }
    this.totalScore  = "Love all";
  }

  firstPlayerScore() {
    this.firstPlayerScoreTimes  ;
  }

  resetGame() {
    this.totalScore = "";
  }
}

module.exports = Tennis;

CodePudding user response:

Remove = in your getScore method in the Tennis class as it will add the new string to the old string.

class Tennis {
  constructor() {
    this.firstPlayerScoreTimes = 0;
    this.totalScore = "";
  }
  getScore() {
    if (this.firstPlayerScoreTimes === 1) {
      this.totalScore = "Fifteen love";
    }
    this.totalScore = "Love all";
  }

  firstPlayerScore() {
    this.firstPlayerScoreTimes  ;
  }

  resetGame() {
    this.totalScore = "";
  }
}

module.exports = Tennis;

CodePudding user response:

Your test is working well, what you need to update is your production code.

Current logic, when firstPlayerScoreTimes is 1, you set the score as Fifteen love and also append Love all string to the score. I guess this is not your requirement. Let's update the getScore function:

  getScore() {
    if (this.firstPlayerScoreTimes === 1) {
      return this.totalScore  = "Fifteen love"; // stop, that's enough 
    }
    this.totalScore  = "Love all";
  }
  • Related