如何使用 jest 模拟提示同步模块

问题描述 投票:0回答:1

我在 Player 类中有这个方法 PromptPlayer ,其作用是将空槽的索引返回给玩家。但在方法内部,我从 JS 的提示同步模块运行提示。似乎无法正确地嘲笑这一点,我已经到处搜索但找不到正确的指南。

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
            }
        }
    }

变量 row 和 col 在测试用例中记录为未定义。

测试。 玩家.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"
        });
    })

})




当我尝试测试提示变量的模拟时,我存储的提示如 row 和 col 仍然未定义,即使我对它们进行了模拟。请让我知道我哪里出错了。

测试进入无限循环,最后它以 row 和 col 中断,我在 console.log 中记录它们是未定义的

javascript unit-testing jestjs mocking jest-mock-extended
1个回答
0
投票

我们应该模拟

create
函数和
prompt
函数。然后,我们可以通过
prompt
 来获取模拟 
mockFn.mock.results
函数。

例如

player.js

const prompt = require('prompt-sync')();

class Player {
  constructor(name, mark) {
    this.name = name;
    this.mark = mark;
  }

  validOption(emptySlots, row, col) {
    //...
  }

  promptPlayer(emptySlots) {
    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);
    console.log('COL IS', col);
  }
}

module.exports = { Player };

player.test.js

const { Player } = require('./player');
const promptSync = require('prompt-sync');

jest.mock('prompt-sync', () => jest.fn(() => 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 = promptSync.mock.results[0].value;

    // Act
    // Mock the input values for row and column
    mockPrompt.mockReturnValueOnce('0').mockReturnValueOnce('2');
    player.promptPlayer(emptySlots);

    // Assert
  });
});

测试结果:


  console.log
    ROW IS 0

      at Player.log [as promptPlayer] (stackoverflow/78770377/player.js:17:13)

  console.log
    COL IS 2

      at Player.log [as promptPlayer] (stackoverflow/78770377/player.js:18:13)

 PASS  stackoverflow/78770377/player.test.js
  Player Class
    √ promptPlayer returns { row, col, mark } (15 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.781 s, estimated 1 s
Ran all test suites related to changed files.
© www.soinside.com 2019 - 2024. All rights reserved.