无法为模块模式编写Jasmine测试

时间:2013-11-04 16:19:38

标签: jasmine

我正在尝试使用Jasmine来测试一个简单的JavaScript类,但我无法确定测试失败的原因。

    // Define the class to be tested

    function Quiz() {
        // private variables
        var score = 1;

        function getScore() {
            return score;
        }

        // public methods
        return {
            getScore: getScore
        };
    }

在运行测试之前,请确认可以调用getScore方法。

    // Get the score outside of the Jasmine test
    var myQuiz = new Quiz();
    var myScore = myQuiz.getScore();
    console.log("myScore = ", myScore);

现在尝试运行测试

    describe("A Quiz", function() {
        it("should have a default score of 1", function() {
            // Get the score inside of the Jasmine test
            var quiz = new Quiz();
            console.log("Quiz object: ", quiz);
            var score = quiz.getScore();
            console.log("score", score);
            expect(score).toBe(1);
        });

    });

以下是运行测试的输出。

A Quiz should have a default score of 1.
    ✘ TypeError: quiz.getScore is not a function in http://localhost:7357/scripts/QuizTest.js (line 26)
        @http://localhost:7357/scripts/QuizTest.js:26
myScore =  1
Quiz object:  {"score":0}

在我运行测试之前,我验证了getScore方法是否可调用。输出中的最后一行来自测试前的console.log语句。这验证了可以找到getScore。

但是,如果我尝试在Jasmine测试中调用getScore方法,则找不到它。记录测验对象将验证只有得分变量和方法可见。

Why can't Jasmine see the method?

1 个答案:

答案 0 :(得分:0)

他不认为函数getScore是因为你在Quiz()里面,你可以通过使用参数或全局变量来解决,你也可以返回Quiz函数()+1得分,或者在一个var参数传递中声明它,或者提供全球分数