afterEach Jest 没有清除我的 totalScore

afterEach Jest not clearing my totalScore

出于某种原因我得到:

第一次测试通过: “爱所有人”

第二次测试失败: 期待:《十五的爱》 收到:“十五爱爱所有”

据我了解,我需要使用 afterEach 来拆除原始配置。我已经试过了,但它似乎没有 'wipe' 总分。

感谢您的帮助!

测试文件:

  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 文件:

    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;

Tennis class 的 getScore 方法中删除 +=,因为它会将新字符串添加到旧字符串。

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;

您的测试运行良好,您需要更新的是生产代码。

目前的逻辑,当firstPlayerScoreTimes为1时,你将分数设置为Fifteen love,并在分数上附加Love all字符串。我想这不是你的要求。让我们更新 getScore 函数:

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