【问题标题】:How to check that jQuery methods (fadeOut, hide, etc) have been called with Jasmine如何检查是否已使用 Jasmine 调用了 jQuery 方法(fadeOut、hide 等)
【发布时间】:2011-12-27 22:01:15
【问题描述】:

我正在尝试通过使用在 Ruby 中对我有用的相同 TDD 方法来清理我的 Javascript,但是跳转到 Jasmine 让我陷入了困境。

举个简单的例子,我想指定给定元素在点击时淡出:

$('.position-details').live 'click', ->
  $this = $(this)
  $this.fadeOut 'fast', ->
    $this.closest('.fields').find('.position-search').fadeIn('fast').focus()

我的规格:

describe "Position picker", ->
  beforeEach ->
    loadFixtures("position_picker.html")
    @details = $('.position-details')
    @picker = $('.position-picker')
    jasmine.Clock.useMock()

  it "the position details are initially shown", ->
    expect(@details).toBeVisible()

  describe "when the position details are clicked", ->
    it "fades out the position details", ->
      @details.trigger('click')
      jasmine.Clock.tick(1000)
      expect(@details).not.toBeVisible()

我的灯具:

<div id='position-data' data-positions="[{&quot;value&quot;:35,&quot;label&quot;:&quot;Accountant&quot;,&quot;division&quot;:&quot;North&quot;,&quot;job_class&quot;:&quot;Headquarters&quot;}]"></div>

<div class='position-details'>
  <div class='position-name'></div>
  <br />
</div>

<div class='position-picker'>
  <label>Position<abbr title="required">*</abbr></label>
  <span class="error" />
  <input class="position-search" type="text" />
  <div>
    <input class="position_id" type="text" />
  </div>
</div>

第一个规范通过了,我不确定为什么第二个没有。一旦我掌握了其中的一些,我相信它会让人感到第二天性。感谢您的帮助或建议!

【问题讨论】:

  • 为什么要测试元素是否不可见。您的代码对此不承担任何责任,但 jquery.因此,如果 jquery 中存在错误,即使您的代码是正确的,您的测试也会失败。您应该测试的只是单击该函数会调用您的元素。
  • 感谢您的帮助。我不想测试 jquery 是否有效,但我已经编写了调用fadeOut 的代码,因为该元素应该是渐变的。我想在语义上我没有以正确的方式测试这个,但我找不到我应该测试这个的方式的例子。如果我的代码应该仍然淡出,我的代码很可能会调用fadeOut。只是有一种不同的方法可以做到这一点,我没有得到,它不是上面的代码。
  • @AndreasKöberle 这个评论很有帮助。如果您将其改写为答案,我会接受。这确实是解决方案。

标签: jquery tdd jasmine jasmine-jquery


【解决方案1】:

您可以使用spyOn

检查一下:

it("fades out the element", function() {
  spyOn($.fn, 'fadeOut');
  fadeOutElem();
  expect($.fn.fadeOut).toHaveBeenCalled();
});

你也可以像这样使用超时:

it("fades out the element", function(done) {
  fadeOutElem();
  setTimeout(300, function() {
    expect($(".position-details").css('display').toEqual('none');
    done();
  });
});

【讨论】:

    【解决方案2】:

    看看这个SO和这个blog post

    【讨论】:

      猜你喜欢
      • 2019-06-06
      • 2021-04-27
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2014-02-02
      相关资源
      最近更新 更多