user10021926
user10021926

Reputation:

Testing class function in JavaScript, Mocha and Chai

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

Upvotes: 0

Views: 2186

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

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 :)

Upvotes: 1

Related Questions