在 JavaScript、Mocha 和 Chai 中测试 class 功能

Testing class function in JavaScript, Mocha and Chai

我创建了一个简单的机器人,想测试一个名为 getComputerChoice 的基本 class 功能。我正在使用 mocha 和 chai 来测试此功能,但是当我 运行 它时,它显示 TypeError: getComputerChoice is not a function。我曾尝试找到解决方案,但没有任何运气。

下面是代码:

game.js

class PaperScissorsRockCommand {
    constructor() {}

    getComputerChoice() {
        const choices = ['paper', 'scissors', 'rock'];
        const chance = Math.floor(Math.random() * 3);
        return choices[chance];
    }
}

module.exports = PaperScissorsRockCommand;

game.spec.js

const assert = require('chai').assert;
const getComputerChoice = require('../commands/games/paperscissorsrock').getComputerChoice;

describe('Paper, Scissors, Rock', function () {
    it('Return paper', function () {
        let result = getComputerChoice();
        assert.equal(result, 'paper');
    });
});

您需要将您的功能标记为静态

class PaperScissorsRockCommand {
    constructor() {}

    static getComputerChoice() {
        const choices = ['paper', 'scissors', 'rock'];
        const chance = Math.floor(Math.random() * 3);
        return choices[chance];
    }
}

正如目前所写,您正在将此方法添加到 PaperScissorsRockCommand.prototype

同时测试使用 Math.random 的函数将很难 w/o 模拟 Math.random :)