![](/img/trans.png)
[英]How to run a function based on variable value which is dependent on other function in specs jasmine?
[英]Jasmine how pass specs that run in any order that depend on a closure variable
我覺得這應該是非常直觀的......但也許它的工作方式與我在 Rspec 中習慣的想法不同......這是我正在嘗試測試的 function:
var finalSet = (function() {
var mount = false
return {
initializePage: function() {
if (mount == false) {
this.mountForm();
mount = true;
}
this.greetCustomer();
},
greetCustomer: function() {
...
},
mountForm: function() {
...
}
}
})();
要點是mount
是一個閉包變量,確保無論調用多少次initializePage
, mountForm
只調用一次。
這是我目前的規格:
describe("finalSet", function() {
describe("initializePage", function() {
beforeEach(function() {
spyOn(finalSet, "mountForm")
spyOn(finalSet, "greetCustomer")
})
describe("first initialization", function() {
beforeEach(function() {
finalSet.initializePage();
})
it("calls both methods", function() {
expect(finalSet.mountForm).toHaveBeenCalled()
expect(finalSet.greetCustomer).toHaveBeenCalled()
})
describe("initialize again", function() {
beforeEach(function() {
finalSet.initializePage();
})
it("repeat calls only greetCustomer", function() {
expect(finalSet.mountForm.calls.count()).toEqual(1)
expect(finalSet.greetCustomer.calls.count()).toEqual(2)
})
})
})
})
})
如果我單獨運行規范,它們就會通過。 一起隨機地,只有一個會通過,第一個運行的規范,第二個總是失敗。
我知道為什么會這樣……但不是為解決此問題而設置的適當 Jasmine。
它發生的原因是因為finalSet
在所有規范中安裝一次,這意味着盡管有兩個規范,但閉包設置一次。 所以如果"first initialization"
測試先運行, beforeEach
對finalSet.initializePage()
的調用設置mount = true
,第一個規范通過,但是接下來, "initialize again" test,
mount is still true, it doesn't reset, so neither of the 2
calls to
will ever call
mountForm`,因為這發生在第一個通過的規范中。 因此第二個規范失敗了。
另一方面,如果"initialize again"
先運行,堆疊的 2 個beforeEach
調用finalSet.initializePage()
將按預期工作, mountForm
被調用一次, greetCustomer
被調用兩次。 但是當第一個"first initialization"
規范被調用時, mount = true
已經存在,所以什么都不會被調用。
直接的問題:有沒有辦法將閉包重置為第一個beforeEach
的一部分?
更大的問題:我已經習慣了 Rspec 中的這種嵌套規范,但是......我覺得也許這不是在 Jasmine 中應該測試的方式,所以非常願意接受更好的測試方法是。
謝謝!
您正在嘗試跨多個規范測試本質上是全局 object 的內容。 您將以某種方式修改您的代碼以測試您想要的內容。 這里有一些想法:
將 reset() function 添加到導出的 object 中,將 mount 變量設置為 false,在規范中的 before/afterEach 中調用此 function。 這類似於您在每次測試之前如何在 Rails 規范中重置數據庫(全局資源)。
讓您的代碼返回 function 而不是立即調用它。 您可以將 finalSet 變量重命名為 createFinalSet。 這意味着您有一個 finalSet 工廠而不是全局實例或 singleton; 每個測試都會通過finalSet = createFinalSet()
擁有自己的 finalSet。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.