2013-10-06 23 views
75

基於this教程測試使用chai的angularjs應用程序,我想使用「should」樣式添加一個未定義值的測試。這種失敗:Chai:如何使用'should'語法測試未定義的

it ('cannot play outside the board', function() { 
    scope.play(10).should.be.undefined; 
}); 

錯誤「類型錯誤:無法讀取屬性‘應該’的不確定」,但測試通過用「期待」的風格:

it ('cannot play outside the board', function() { 
    chai.expect(scope.play(10)).to.be.undefined; 
}); 

我怎樣才能得到它一起工作「應該」?

+1

這是很容易,如果你會用「斷言」,你可以做到這一點的'assert.isUndefined(範圍.play(10))' – lukaserat

回答

65

這是的缺點應該語法之一。它通過將should屬性添加到所有對象來工作,但如果未定義返回值或變量值,則不存在用於保存該屬性的對象。

documentation給出了一些解決方法,例如:

var should = require('chai').should(); 
db.get(1234, function (err, doc) { 
    should.not.exist(err); 
    should.exist(doc); 
    doc.should.be.an('object'); 
}); 
+11

'should.not.exist'將驗證值是否爲'null',所以此答案不正確。 @daniel的答案如下:'should.equal(testedValue,undefined);'。這應該是被接受的答案。 – Sebastian

+5

我每月都會回答這個問題(不是文檔):-) –

4

試試這個:

it ('cannot play outside the board', function() { 
    expect(scope.play(10)).to.be.undefined; // undefined 
    expect(scope.play(10)).to.not.be.undefined; // or not 
}); 
+0

謝謝,但這就是我在上面的第二次嘗試中所做的。我想了解如何使用[should](http://chaijs.com/guide/styles/#should)語法來實現。 – thebenedict

0

可以在should()包裝你的函數結果和試驗一種 「不確定」:

it ('cannot play outside the board', function() { 
    should(scope.play(10)).be.type('undefined'); 
}); 
37
should.equal(testedValue, undefined); 

如前所述in chai documentation

+12

omg,有什麼解釋?您期望testedValue爲===未定義,因此您可以對其進行測試。許多開發人員首先首先將testsValue進行了測試,然後將其與should鏈接起來,最後發現錯誤... – daniel

+5

這並不適用於開箱即用,它在[.equal()的API文檔中找不到) '](http://chaijs.com/api/bdd/#method_equal)。我可以理解爲什麼@OurManInBananas要求解釋。這是應用程序的一個意外使用,它接受兩個參數,而不是預期的鏈接方法形式接受期望值的單個參數。您只能通過導入/要求並分配被調用版本的'.should()'來實現這一點,如@DavidNorman接受的答案中所述,並且在[documentation](http://chaijs.com/guide/styles/#應該-演員)。 – gfullam

+0

我想你會發現'.equal'語法產生好得多的錯誤消息,因爲它允許你輸出更具描述性的消息,當事情失敗時 – jcollum

15
(typeof scope.play(10)).should.equal('undefined'); 
1

根據文檔,@ david-norman的答案是正確的,我在安裝時遇到了一些問題,而選擇了以下選項。

(typeof scope.play(10))。should.be.undefined;在條件

var should = require('should'); 
... 
should(scope.play(10)).not.be.ok; 
+0

'typeof'運算符返回一個**字符串**;所以這個斷言不能通過; cuz''undefined'!== undefined' – dNitro

15

測試未定義

var should = require('should'); 
... 
should(scope.play(10)).be.undefined; 

測試空

var should = require('should'); 
... 
should(scope.play(10)).be.null; 

試驗falsy,即我掙扎着寫未定義應聲明試驗。以下不起作用。

target.should.be.undefined(); 

我發現了以下解決方案。

(target === undefined).should.be.true() 

如果還可以把它寫成一個類型檢查

(typeof target).should.be.equal('undefined'); 

不知道上面是正確的做法,但它確實工作。

According to Post from ghost in github

+0

不是特別有用或直觀,但這很聰明! – thebenedict

+2

沒用?這是在bdd樣式IMO中未定義測試的最佳答案,但是它需要安裝其他npm軟件包(應用軟件包),並且我認爲不值得爲其安裝其他軟件包,儘管 –

6

視爲虛假

+0

值得注意的是使用此語法可能會導致JavaScript將括號化表達式解釋爲嘗試將前一行作爲函數調用(如果您不以分號結尾行)。 – bmacnaughton

0

不要忘記的havenot關鍵字的組合:

const chai = require('chai'); 
chai.should(); 
// ... 
userData.should.not.have.property('passwordHash'); 
相關問題