2016-05-19 5 views
0

カルマによってテストが実行されていますが、そのうちの1つでは、オブジェクトのnew instanceを作成し、functionを使用します(this)。通常のブラウザでthisが現在のインスタンスへの参照ですが、テストでconsole.log後に、それは私が参照してください。テスト新しいオブジェクトインスタンス(ジャスミン)

オブジェクト{文書:!<を - これは、実行コンテキストです。

iframe内にロードされます。すべての実行が実行される前にリロードされます。

なぜですか? window

// createing the object 
 

 
window.gr = window.gr || {}; 
 

 
gr.Notification = (function() { 
 
    function Notification(node, message) { 
 
     this.liveTime = 5000; 
 
     this.template = this.createTemplate(message); 
 
     this.node = null; 
 
     this.appendTo(node); 
 

 
     setTimeout(this.remove, this.liveTime); 
 
    } 
 

 
    Notification.prototype = { 
 
     createTemplate: function (message) { 
 
      var notification = document.createElement("div"); 
 
      notification.className = "notification"; 
 

 
      var _message = document.createTextNode(message); 
 
      notification.appendChild(_message); 
 

 
      return notification; 
 
     }, 
 
     appendTo: function(node){ 
 
      this.node = node.appendChild(this.template); 
 
     }, 
 
     remove: function(){ 
 
      console.log(this) 
 
      this.node.parentNode.removeChild(this.node); 
 
     } 
 
    }; 
 

 
    return Notification; 
 
})(); 
 

 

 
//test 
 

 
beforeEach(function(){ 
 
     Notification = gr.Notification; 
 
     jasmine.clock().install(); 
 
    }); 
 

 
it("should remove notification after 5s", function(){ 
 
     new Notification(document.body); 
 

 
     jasmine.clock().tick(5001); 
 

 
     expect(document.querySelectorAll(NOTIFICATION_SELECTOR).length).toEqual(0); 
 
    });

+0

要約ではなく実際のコードを含めることができれば非常に役に立ちます。正確な動作は、オブジェクトの呼び出し方法と場所によって変わることがあります。 – ssube

+0

何が起こっているのかは文脈なしでは分かりませんが、Jasmineそれぞれの "it"の後に本体の内容をきれいにして、beforeEachの中でこの新しいインスタンスを作成しようとしましたか? –

+0

投稿を編集してコードを追加します – Alcadur

答えて

0

あなたthis言及、あなたはwindowwindowオブジェクトのメソッドであるのsetTimeout、そのための方法のポイント内部thisを呼び出すので、

あなたはそのような何かを行うことができます:

function Notification(node, message) { 
     this.liveTime = 5000; 
     this.template = this.createTemplate(message); 
     this.node = null; 
     this.appendTo(node); 

     var self = this; 

     setTimeout(function() { 
      self.remove() 
     }, self.liveTime); 

    } 
関連する問題