繁体   English   中英

在JavaScript,Mocha和Chai中测试类函数

[英]Testing class function in JavaScript, Mocha and Chai

我创建了一个简单的漫游器,并想要测试一个名为getComputerChoice的基本类函数。 我正在使用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的函数,而不会模拟Math.random

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM