簡體   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