2013-11-04 46 views
0

我想用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? 

回答

0

,他不认为该函数getScore因为你是内部测验(),您可以通过使用参数或全局变量解决,你也可以返回测验功能()+1分,或者在一个声明它var参数传递,或饲喂全球得分