如何使用jasmine测试具有setTimeout的函数?

问题描述 投票:41回答:4

我需要为一个内部有setTimeout()调用的函数编写测试,但我无法找到应该怎么做。

这是功能

// Disables all submit buttons after a submit button is pressed.
var block_all_submit_and_ajax = function( el ) {
    // Clone the clicked button, we need to know what button has been clicked so that we can react accordingly
    var $clone = $( el ).clone();
    // Change the type to hidden
    $clone.attr( 'type', 'hidden' );
    // Put the hidden button in the DOM
    $( el ).after( $clone );
    // Disable all submit button. I use setTimeout otherwise this doesn't work in chrome.
    setTimeout(function() {
         $( '#facebook input[type=submit]' ).prop( 'disabled', true );
     }, 10);
    // unbind all click handler from ajax
    $( '#facebook a.btn' ).unbind( "click" );
    // Disable all AJAX buttons.
    $( '#facebook a.btn' ).click( function( e ) {
        e.preventDefault();
        e.stopImmediatePropagation();
    } );
};

这是我的考验

it( "Disable all submit buttons", function() {
    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );
    // Call the function
    utility_functions.block_all_submit_and_ajax( $button.get(0) );
    // check that all submit are disabled
    $( '#facebook input[type=submit]' ).each( function( i, el ) {
        console.log( 'f' );
        expect( el ).toHaveProp( 'disabled', true );
    } );
} );

我尝试过使用jasmine.Clock.useMock();jasmine.Clock.tick(11);,但我无法让事情发挥作用,测试从未通过

javascript jquery unit-testing settimeout jasmine
4个回答
63
投票

整体方法因您的Jasmine版本而异。

Jasmine 1.3

你可以使用waitsFor

it( "Disable all submit buttons", function() {
    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );
    // Call the function
    utility_functions.block_all_submit_and_ajax( $button.get(0) );

    // Wait 100ms for all elements to be disabled.
    waitsFor('button to be disabled', function(){
        var found = true;
        // check that all submit are disabled
        $( '#facebook input[type=submit]' ).each( function( i, el ) {
            if (!el.prop('disabled')) found = false;
        });
        return found;
    }, 100);
});

如果您确切知道需要多长时间,也可以使用waits

it( "Disable all submit buttons", function() {
    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );
    // Call the function
    utility_functions.block_all_submit_and_ajax( $button.get(0) );

    // Wait 20ms before running 'runs' section.
    waits(20);

    runs(function(){
        // check that all submit are disabled
        $( '#facebook input[type=submit]' ).each( function( i, el ) {
            expect( el ).toHaveProp( 'disabled', true );
        });
    });
});

还有第三种方法,不需要waitswaitsForruns

it( "Disable all submit buttons", function() {
    jasmine.Clock.useMock();

    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );
    // Call the function
    utility_functions.block_all_submit_and_ajax( $button.get(0) );

    jasmine.Clock.tick(10);

    // check that all submit are disabled
    $( '#facebook input[type=submit]' ).each( function( i, el ) {
        expect( el ).toHaveProp( 'disabled', true );
    });
});

Jasmine 2.0

你可以使用done,测试回调:

it( "Disable all submit buttons", function(done) {
    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );

    utility_functions.block_all_submit_and_ajax( $button.get(0) );

    setTimeout(function(){
        // check that all submit are disabled
        $( '#facebook input[type=submit]' ).each( function( i, el ) {
            expect( el ).toHaveProp( 'disabled', true );
        });

        // Let Jasmine know the test is done.
        done();
    }, 20);
});

你可以模拟出计时器的行为:

it( "Disable all submit buttons", function() {
    jasmine.clock().install();

    // Get a button
    var $button = $( '#ai1ec_subscribe_users' );
    // Call the function
    utility_functions.block_all_submit_and_ajax( $button.get(0) );

    jasmine.clock().tick(10);

    // check that all submit are disabled
    $( '#facebook input[type=submit]' ).each( function( i, el ) {
        expect( el ).toHaveProp( 'disabled', true );
    });

    jasmine.clock().uninstall()
});

3
投票

我从来没有用茉莉花做任何测试,但我想我理解你的问题。我会稍微重构一下代码以允许你在这样的代理函数中包装被调用的函数:

修改正在测试的代码以将setTimeout代码提取到另一个函数中:

原始代码:

// Disables all submit buttons after a submit button is pressed. 
var block_all_submit_and_ajax = function( el ) { 
    // Clone the clicked button, we need to know what button has been clicked so that we can react accordingly 
    var $clone = $( el ).clone(); 
    // Change the type to hidden 
    $clone.attr( 'type', 'hidden' ); 
    // Put the hidden button in the DOM 
    $( el ).after( $clone ); 
    // Disable all submit button. I use setTimeout otherwise this doesn't work in chrome. 
    setTimeout(function() { 
        $( '#facebook input[type=submit]' ).prop( 'disabled', true ); 
    }, 10); 
    // unbind all click handler from ajax 
    $( '#facebook a.btn' ).unbind( "click" ); 
    // Disable all AJAX buttons. 
    $( '#facebook a.btn' ).click( function( e ) { 
        e.preventDefault(); 
        e.stopImmediatePropagation(); 
    } ); 
};

修改代码:

// Disables all submit buttons after a submit button is pressed. 
var block_all_submit_and_ajax = function( el ) { 
    // Clone the clicked button, we need to know what button has been clicked so that we can react accordingly 
    var $clone = $( el ).clone(); 
    // Change the type to hidden 
    $clone.attr( 'type', 'hidden' ); 
    // Put the hidden button in the DOM 
    $( el ).after( $clone ); 
    // Disable all submit button. I use setTimeout otherwise this doesn't work in chrome. 
    setTimeout(disableSubmitButtons, 10); 
    // unbind all click handler from ajax 
    $( '#facebook a.btn' ).unbind( "click" ); 
    // Disable all AJAX buttons. 
    $( '#facebook a.btn' ).click( function( e ) { 
        e.preventDefault(); 
        e.stopImmediatePropagation(); 
    } ); 
};

var utilityFunctions =
{
  disableSubmitButtons : function()
  {
    $( '#facebook input[type=submit]' ).prop( 'disabled', true ); 

  }
}

接下来我会像这样修改测试代码:

it( "Disable all submit buttons", function() { 
    // Get a button 
    var $button = $( '#ai1ec_subscribe_users' ); 

    var originalFunction = utilityFunctions.disableSubmitButtons;
    utilityFunctions.disableSubmitButtons = function()
    {
        // call the original code, and follow it up with the test
        originalFunction();

        // check that all submit are disabled 
        $( '#facebook input[type=submit]' ).each( function( i, el ) { 
            console.log( 'f' ); 
            expect( el ).toHaveProp( 'disabled', true ); 
        }); 

        // set things back the way they were
        utilityFunctions.disableSubmitButtons = originalFunction;
    }

    // Call the function 
    utility_functions.block_all_submit_and_ajax( $button.get(0) ); 
}); 

3
投票

从Jasmine 2开始,语法发生了变化:http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

你现在可以简单地将done回调传递给beforeEachitafterEach

it('tests something async', function(done) {
    setTimeout(function() {
        expect(somethingSlow).toBe(true);
        done();
    }, 400);
});

更新:自写这篇文章以来,现在也可以使用async/await,这将是我的首选方法。


1
投票

对于任何使用Google搜索的人,可以找到更好的答案timer testing

import { fakeAsync, tick, discardPeriodicTasks } from '@angular/core/testing';

it('polls statusStore.refreshStatus on an interval', fakeAsync(() => {
  spyOn(mockStatusStore, 'refreshStatus').and.callThrough();
  component.ngOnInit();
  expect(mockStatusStore.refreshStatus).not.toHaveBeenCalled();
  tick(3001);
  expect(mockStatusStore.refreshStatus).toHaveBeenCalled();
  tick(3001);
  expect(mockStatusStore.refreshStatus).toHaveBeenCalledTimes(2);
  discardPeriodicTasks();
 }));
© www.soinside.com 2019 - 2024. All rights reserved.