5

这对其他人来说可能很明显,但我没有通过搜索找到它,因此在此处发布问题和一个可能的答案。

背景:

  1. 使用小部件工厂自定义 JQuery UI 小部件
  2. 在小部件中,某些元素会根据其他数据/选项隐藏或显示。
  3. 创建单元测试以验证它们是否正确显示/隐藏。
  4. 我认为我的单元测试都可以在内存中创建自己的元素,类似于这个旧答案

从这个例子中去掉了实际的小部件部分:

test( 'show/hide', 1, function() {
    var somecondition = true;

    var div = $( '<div/>' ).hide();
    if (somecondition) div.show();

    equal( somecondition, div.is( ":visible" ) );
});

测试失败,因为 jQuery 总是报告div.is( ":visible" )为假。我认为使用div.css('display') == 'none'将是一种解决方法。不幸的是,这在 Chrome 中有效,但在 Firefox 中无效。

4

1 回答 1

7

The problem was that jQuery is smart enough to know that even if a particular element has said it's visible, it might not actually be visible if (for example):

  1. It was never added to the DOM
  2. The DOM element (or parent/grandparent/etc) it was appended to is not actually visible

So in order for the unit tests to work, I need to have a real div in the test harness html, attach the widget to it, and then call a destroy at the end.

test( 'show/hide', 1, function() {
    var somecondition = true;

    var div = $( '#someid' ).hide();
    if (somecondition) div.show();

    equal( somecondition, div.is( ":visible" ) );
});

I was hoping for a different approach (and maybe someone will come along and provide another answer), but I'm not very hopeful, seeing as this is the approach that JQueryUI uses in their own QUnit tests:

test( "search, close", function() {
    //SNIP
    // Note the use of a real element here:
    element = $( "#autocomplete" ).autocomplete({
        source: data,
        minLength: 0
    }),
    menu = element.autocomplete( "widget" );
    //SNIP
    ok( menu.is( ":visible" ), "menu is visible after search" );
    //SNIP
});
于 2013-04-16T21:06:38.027 回答