我正在编写Jasmine测试,但它显示出奇怪的行为。
这是我的代码:
root = exports ? this
class root.SomeClass
constructor: ->
@index = 0
incrementIndex: -> @index++
decrementIndex: -> @index--
这是我的测试代码:
describe "Object", ->
object = new SomeClass
describe ".index", ->
describe "when index = 3", ->
object.index = 3
describe "when next button is clicked", ->
object.incrementIndex()
it "returns 4", ->
expect(object.index).toBe 4
describe "when previous button is clicked", ->
object.decrementIndex()
it "returns 3", ->
expect(object.index).toBe 2
测试结果如下:
Failing 2 specs
Photos initialized .index when index = 3 when next button is clicked returns 4.
Expected 3 to be 4.
Photos initialized .index when index = 3 when previous button is clicked returns 3.
Expected 3 to be 2.
奇怪的是当我评论最后4行测试代码时,测试通过。我无法理解发生了什么......> _<
感谢您的帮助。
答案 0 :(得分:3)
您的测试互相影响。 Do setup in beforeEach
blocks
describe "Object", -> object = undefined beforeEach -> object = new SomeClass describe ".index", -> describe "when index = 3", -> beforeEach -> object.index = 3 describe "when next button is clicked", -> beforeEach -> object.incrementIndex() it "returns 4", -> expect(object.index).toBe 4 describe "when previous button is clicked", -> beforeEach -> object.decrementIndex() it "returns 3", -> expect(object.index).toBe 2
未检查此段代码是否有效,但仍显示您应如何修复测试。注意2行中的object = undefined
。您需要在此处声明变量,否则object
将是每个beforeEach
和it
块的本地变量。