测试新对象实例(茉莉花)

test new object instance (jasmine)

我有 karma 测试 运行,在其中一个中我创建了 new instance 对象并调用了 function,其中使用了 this。在普通浏览器上,this 是对当前实例的引用,但在 console.log 之后的测试中,我看到:

Object{document: < !-- This is the execution context.

Loaded within the iframe. Reloaded before every execution run.

为什么?

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

你的this引用了window,因为你调用了setTimeout,它是window对象的方法,所以那个方法里面的this指向window,

你可以这样做:

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

    }