0

I have created a simple bot and want to test a basic class function called getComputerChoice. I am using mocha and chai to test this function but when I run it, it says TypeError: getComputerChoice is not a function. I have tried finding a solution but haven't had any luck.

Here is the code below:

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');
    });
});

1 Answer 1

1

You need to mark you function as static

class PaperScissorsRockCommand {
    constructor() {}

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

As currently written you were adding this method to PaperScissorsRockCommand.prototype

Also testing a function that uses Math.random would be hard w/o mocking Math.random :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that. It worked but I get the problem where if it isn't paper, I get an error. How could I test it with the random as you mentioned @YuryTarabanko
You need to mock Math.random to return the value you need for testing purposes. Google "javascript mocking" For example blog.kentcdodds.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.