2017-08-17 67 views
-1

我想添加單元測試這一功能:我們如何添加單元測試的JavaScript hasOwnProperty()函數

var advance = function (des, source) { 
     for (var p in source) { 
      if (source.hasOwnProperty(p)) { 
       des[p] = source[p]; 
      } 
     } 
     return des; 
}; 

我們如何檢查茉莉花hasOwnProperty()方法?

編輯: 可能的解決方法

var des; 
var source; 
beforeEach(function() { 
    des = {}; 
    source = { 
     p: 'value', 
     p1: 'value1' 
    }; 
}); 

beforeAll(function() { 
    advance(des, source); 
}); 

it('should has a property with the name of the argument', function() { 
    expect(source).toEqual(jasmine.objectContaining({ 
     p: 'value' 
    })); 
    expect(source).not.toEqual(jasmine.objectContaining({ 
     p2: 'value2' 
    })); 
}); 

一個人,請提出更好的解決方案。

+0

更好的解決方案是什麼?你目前的單元測試是什麼? –

+0

而且不做交叉標記。 Java!= JavaScript! – GhostCat

+0

什麼_better_解決方案?你沒有提供你自己的嘗試。 –

回答

2

hasOwnProperty()如果指定的屬性名稱只是對象本身的一部分,而不是原型鏈,則返回true。

因此,你可以通過對樣機這樣創建一個屬性「模擬」這樣一個對象:

function Foo() { 
    // own properties of "src" 
    this.a = 1; 
    this.b = 2; 
} 
// not own property of "src" 
Foo.prototype.c = 1; 
src = new Foo(); 

你的測試可能是這樣的:

describe("hasOwnProperty", function() { 
    var dest, src; 

    beforeEach(function() { 
     dest = { }; 

     function Foo() { 
      this.a = 1; 
      this.b = 2; 
     } 
     Foo.prototype.c = 3; 
     src = new Foo(); 

     advance(dest, src); 
    }); 

    it("should not pick non-own properties", function() { 
     expect(dest.c).not.toBeDefined(); 
    }); 

    it("should pick own property", function() { 
     expect(dest.a).toBe(1); 
     expect(dest.b).toBe(2); 
    }); 
}); 

這將失敗的測試:

function Foo() { 
    this.a = 1; 
    this.b = 2; 
    // Own property - spec demands this to be undefined 
    this.c = 3; 
} 
// Defined (above) as own property instead 
// Foo.prototype.c = 3; 
src = new Foo(); 
+0

感謝您的好解釋:) – supun94

相關問題