与问题一样,我的测试应该尽可能简单,还是应该包含一些模仿我正在测试的函数逻辑的逻辑?
举个例子,我正在测试这个功能:
$( 'ul.nav-tabs a' ).click( event_handlers.handle_set_tab_cookie );
var handle_set_tab_cookie = function( e ) {
var active = $( this ).attr( 'href' );
$.cookie( 'feeds_active_tab', active );
};
我的测试应该像这样愚蠢:
describe( "Facebook Feeds page", function() {
beforeEach( function() {
$( 'ul.nav' ).remove();
var html = $('<ul class="nav nav-tabs"><li class="active"><a data-toggle="tab" href="#facebook">Facebook Feeds</a></li><li class=""><a data-toggle="tab" href="#ics">ICS</a></li></ul>');
$('body').append( html );
} )
it( "Should call jQuery cookie to save the href ", function() {
// Set up the listeners
page.start();
// Set up spies
spyOn($, 'cookie');
// Start the test
var a = $( 'a[href=#facebook]' );
a.trigger( 'click' );
// verify that it has been called with the correct parameter
expect($.cookie).toHaveBeenCalled();
expect($.cookie).toHaveBeenCalledWith('feeds_active_tab', '#facebook');
} );
afterEach( function() {
$( 'ul.nav' ).remove();
} );
} );
或者有一些迭代/逻辑,以便我一次完成所有测试?
describe( "Facebook Feeds page", function() {
beforeEach( function() {
$( 'ul.nav' ).remove();
var html = $('<ul class="nav nav-tabs"><li class="active"><a data-toggle="tab" href="#facebook">Facebook Feeds</a></li><li class=""><a data-toggle="tab" href="#ics">ICS</a></li></ul>');
$('body').append( html );
} )
it( "Should call jQuery cookie to save the href ", function() {
// Set up the listeners
page.start();
// Set up spies
spyOn($, 'cookie');
// Start the test and iterate over all the links
$( 'ul.nav a' ).each( function(i, el) {;
$(el).trigger( 'click' );
// verify that it has been called with the correct parameter
expect($.cookie).toHaveBeenCalled();
expect($.cookie).toHaveBeenCalledWith('feeds_active_tab', $(el).attr('href');
} );
} );
afterEach( function() {
$( 'ul.nav' ).remove();
} );
} );