2016-04-22 30 views
0

我剛剛開始使用TDD,而且我遇到了一個奇怪的問題。我爲一個(也是簡單的)user模塊寫了一個非常簡單的測試。由於某種原因,測試表示hasOwnProperty函數不存在。沒有找到柴的功能

測試代碼:

var expect = require('chai').expect; 
var user = require('./user'); 

describe('Name', function() { 
    it('Should have a name', function() { 
    expect(user).to.have.ownProperty('name'); 
    }); 
    it('The name property should be a string', function() { 
    expect(user.name).to.be.a('string'); 
    }); 
    it('Should have non empty string as name', function() { 
    expect(user.name).to.have.length.above(0); 
    }); 
}); 

模塊:

var user = Object.create(null); 

user.name = 'Name'; 

// exports 
module.exports = user; 

運行$ mocha test.js之後,第一測試失敗。 Chai ownProperty reference

有什麼建議嗎?謝謝!

控制檯輸出:

Name 
    1) Should have a name 
    ✓ The name property should be a string 
    ✓ Should have non empty string as name 


2 passing (12ms) 
1 failing 

1) Name Should have a name: 
    TypeError: obj.hasOwnProperty is not a function 
    at Assertion.assertOwnProperty (node_modules/chai/lib/chai/core/assertions.js:937:13) 
    at Assertion.ctx.(anonymous function) [as ownProperty] (node_modules/chai/lib/chai/utils/addMethod.js:41:25) 
    at Context.<anonymous> (test.js:6:26) 
+0

張貼您的控制檯日誌請致電 –

回答

1

Object.create(null)意味着用於創建對象的用戶的原型爲空,因此它不繼承「物件」型的屬性。

試試這個。

var user = Object.create({}); 

user.name = 'Name'; 

// exports 
module.exports = user; 

您將需要使用Object.create({}),有機會獲得hasOwnProperty方法。

+0

感謝您的驚人迴應!然而,我確實有1 q:你怎麼知道'ownProperty'函數實際上映射到'Object.prototype.hasOwnProperty'?我認爲這只是Chai – aryzing

+0

提供的一個函數。那麼,Chai只是一個測試庫,它仍然需要訪問Javascript對象原型來確定某個屬性是否爲'ownProperty'。沒有其他方法來檢查一個屬性是否屬於自己的屬性。 –

+0

非常感謝! – aryzing