I have this method promptPlayer in the class Player which job is to return to the player the index of an empty slot. But inside the method I am running prompt from the prompt-sync module of JS. Cant seem to mock this properly I have searched everywhere but cant find a correct guide.
player.js
const prompt = require("prompt-sync")();
class Player {
constructor(name, mark) {
this.name = name
this.mark = mark
}
validOption(emptySlots, row, col) {
// if empty slot return false its valid option
// if occopied slot return false its invalid option
if (typeof(row) !== "number" || typeof(col) !== "number") {
return false;
}
row = parseInt(row);
col = parseInt(col);
if (row >= 3 || col >= 3) {
return false;
}
if (emptySlots[row][col] === ".") {
return true;
}
return false;
}
promptPlayer(emptySlots) {
// console.log("Choose an empty slot.");
let row = prompt("Enter the row number (0, 1, or 2): ");
let col = prompt("Enter the column number (0, 1, or 2): ");
console.log("ROW IS", row); // logs undefiend in the test case
console.log("COL IS", col); // logs undefiend in the test case
const isValid = this.validOption(emptySlots, row, col);
if (!isValid) {
console.log("Invalid selection please select the expected values.");
console.log();
return this.promptPlayer(emptySlots);
} else {
return {
row: parseInt(row),
col: parseInt(col),
mark: this.mark
}
}
}
The variables row and col logs as undefined on the test case.
TEST.
player.test.js
const each = require("jest-each").default;
const { Player } = require("../player");
// Mock the prompt-sync module
jest.mock("prompt-sync", () => () => jest.fn());
let player;
let emptySlots;
describe("Player Class", () => {
beforeEach(() => {
player = new Player("Player 1", "X");
emptySlots = [
["X", ".", "."],
["O", ".", "."],
[".", ".", "."]
];
});
afterEach(() => {
jest.clearAllMocks(); // Clear mock calls between tests
})
it("promptPlayer returns { row, col, mark }", () => {
// Arrange
const mockPrompt = require("prompt-sync")();
// Act
// Mock the input values for row and column
mockPrompt.mockReturnValueOnce("0").mockReturnValueOnce("2");
const result = player.promptPlayer(emptySlots);
// Log to verify . does n
console.log("Result:", result);
// Assign
expect(result).toEqual({
row: 0,
col: 2,
mark: "X"
});
})
})
As I have tried the testing the mocking for prompt the variable I am storing the prompt like row and col are still undefined even when I have done mock on them. Please kindly let me know where I am going wrong here.
The test goes into infinite loop in the end it breaks off with row and col where I console.log them that they are undefined