YUI.Test断言在事件的回调中不会失败

时间:2013-08-09 08:31:46

标签: javascript unit-testing continuous-integration yui assertions

我使用的是3.4.0版本

我对YUI.Test断言有一个奇怪的问题。这是一个例子:

YUI().use('test', 'node', 'node-event-simulate',
    function(Y) {
        var runner = Y.Test.Runner;

        var someTestCase = new Y.Test.Case({
            name    : 'SomeMeaningfulName',

            setUp       : function() {
                var test = this;

                // create show details link
                test.Y$aLink    = Y.Node
                                    .create('<a href="//some.fake.url.ie">Show details</a>');

                Y.one('body')
                    .append(test.Y$aLink);                        
            }, 

            tearDown    : function() {
                this.Y$aLink.remove();
            },

            testEventListener : function() {
                var test = this;

                test.Y$aLink
                    .on('click', function(e) {
                        e.preventDefault();

                        // this codes works
                        console.log('on click event');

                        // this one doesn't fail
                        // it "works" perfectly when it's outside of the callback
                        Y.assert(false, 'false is true');
                    });

                test.Y$aLink.simulate('click');
            }
        });

        runner.add(someTestCase);
        runner.run();
    });

当它在事件的回调中时,断言永远不会失败:( 文档没有提到这种情况......

也许我做错了什么,但缺乏文档使得很难确定......

更新

没有等待/恢复的示例: http://jsfiddle.net/op1ekun/Fgra6/2/

和等待/恢复的人 http://jsfiddle.net/op1ekun/Fgra6/5/

UPDATE2

有一个类似的案例已经报道,它涉及异步测试问题,但这不是我的问题: http://yuilibrary.com/projects/yuitest/ticket/74

UPDATE3

这似乎正是我所遇到的并且看起来已经是Billy提出的解决方案,有趣的是使用依赖注入,它可能值得一试: http://csausdev.wordpress.com/2011/02/12/unit-testing-callbacks-with-yui-test/

请帮忙! 谢谢!

1 个答案:

答案 0 :(得分:1)

YUI Test在这种情况下有一个等待和恢复机制。您告诉它等到调用resume方法,resume方法进行回调,您可以安全地进行断言。在你的情况下,它看起来像这样:

'test event listener': function () {
  var test = this;

  test.Y$aLink.on('click', function (e) {
    e.preventDefault();

    test.resume(function () {
      Assert.fail('ouch!');
    });
  });

  test.wait();
  test.Y$aLink.simulate('click');
}