0

我正在编写 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行测试代码时,测试通过了。我无法理解发生了什么...>_<

感谢您的帮助。

4

1 回答 1

3

您的测试相互影响。 beforeEach为单位进行设置。

描述“对象”,->
  对象=未定义

  之前 ->
    对象 = 新的 SomeClass

  描述“.index”,->
    描述“当索引 = 3”,->
      之前 ->
        对象.index = 3

      描述“单击下一个按钮时”,->
        之前 ->
          object.incrementIndex()

        它“返回 4”,->
          期望(object.index).toBe 4

      描述“单击上一个按钮时”,->
        之前 ->
          object.decrementIndex()

        它“返回 3”,->
          期望(object.index).toBe 2

未检查这段代码是否有效,但仍显示您应该如何修复测试。请注意object = undefined第 2 行。您需要在此处声明变量,否则object将对每个beforeEachit块都是本地的。

于 2012-12-17T10:02:58.260 回答