3

I'm starting to write Qunit tests for my existing jQuery plugins. I've gotten through a half dozen configuration style tests just to make sure everything is wired up properly. Now I'm starting to test functionality. My plugin is a countdown style plugin for textarea fields. Here's the actual working version:

http://andymatthews.net/code/textCounter/

I'm writing a test that checks that the count displayed under the field is the correct value. For example, if a field allows 100 characters and 20 characters are in the field when the page loads, the label under the field should read 80.

Here's whats in qunit-fixture:

<div id="qunit-fixture">
    <textarea id="myTextarea">Existing content</textarea>
    <span id="theCounter"></span>
</div>

Here's the pertinent failing test

test('setup', function(){
    console.log($('#theCounter'));
    equal($('#theCounter').text(), 124, 'count correctly initialized');
});

And here's the existing contents of the plugin. There is more to it, but I'm only adding more code as existing tests pass muster.

(function($) {
    $.fn.textCounter = function(o){
        o = $.extend( {}, $.fn.textCounter.defaults, o );
        return this.each(function(i, el){
            var $e = $(el),
                $target = $(o.target);
            // predefined count minus existing content
            $e.html(o.count - $target.text().length);
            console.log( $e.html() );
        });
    }
    $.fn.textCounter.defaults = {
        count: 140,
        alertAt: 20,
        warnAt: 0,
        target: '#myTextarea',
        stopAtLimit: false
    }
}(jQuery));

I'm assuming that since I'm not explicitly configuring the plugin on the test harness page that the plugin using the defaults. If that's the case then the counter should start with max of 140 characters minus the 16 characters already in the field and should display 124.

Here's the problem...when a sample HTML page runs, it correctly displays 124. When the test runs, it returns $('#theCounter').text() as an empty string. Viewing the console after running the sample page AND the test, the log statement above shows 124. But the unit test shows an empty string.

This isn't anything secret so I can provide all of the files if it helps. I'm sure it's probably some sort of scope problem but I'm not experienced enough with QUnit to know what's wrong.

4

1 に答える 1

1

プラグインを呼び出すコードが表示されません。次のことを試してみてください...

test( "setup", function() {
    equal( 
        $( "#theCounter" ).textCounter().text(), 
        124, 
        "Count correctly initialized" 
    );
});

または、モジュールを作成して、セットアップフェーズでそれを行うことができます

var textCounter;

module( "Setup", {
    setup: function() {
        textCounter = $( "#theCounter" ).textCounter();
    },
    teardown: function() {
    }
});

test( "setup", function() {
    equal( textCounter.text(), 124, "Count correctly initialized" );
});

qunit-fixtureマークアップが含まれている場合は、テストごとにリセットされることを知っておくことが重要です。

于 2012-06-22T16:08:41.960 に答える