Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test function that calls Ember.run.debounce in ember-qunit?

The controller I would like to test contains the following:

filterText: '',
filteredFoos: (Ember.A()),

filterFoosImpl: function() {
    console.log('filterFoos begin' );
    var filterText = this.get('filterText');
    var filteredFoos = this.forEach(function(foo) {
        return (foo.get(name).indexOf(filterText) >= 0);
    });
    this.set('filteredFoos', filteredFoos);
},

filterFoos: function() {
    Ember.run.debounce(this.filterFoosImpl.bind(this), 300);
}.observes('model', 'filterText'),

Now I would like to write a test that asserts that filteredFoos is updated when I set filterText.

To do this correctly, I will need to take into account Ember.run.debounce, and wait for that to occur before I perform my assertion. How can I do this?

like image 561
bguiz Avatar asked Oct 01 '22 08:10

bguiz


2 Answers

I was running into this problem as well and in order to stub out debounce, I did the following:

test('it triggers external action on a keyup event', function() {
    expect(1);

    // stub out the debounce method so we can treat this call syncronously
    Ember.run.debounce = function(target, func) {
      func.call(target);
    };

    var component = this.subject();
    var $component = this.append();

    var targetObject = {
      externalAction: function() {
        ok(true, 'external action called');
      }
    };

    component.set('keyUpAction', 'externalAction');

    component.set('targetObject', targetObject);

    $component.keyup();
});

The component I was testing looks like this:

export default Ember.TextField.extend({    
  triggerKeyUpAction: function() {
    this.sendAction('keyUpAction', event);
  },

  keyUp: function(/*event*/) {
    Ember.run.debounce(this, this.triggerKeyUpAction, 200);

    if(!this.get('value')){
      return;
    }

    this.set('value', String(this.get('value')).replace(/[^\d\.\,]/g, ''));
  }
});
like image 107
Jason Buckner Avatar answered Oct 12 '22 23:10

Jason Buckner


Add

await settled();

Before your assertion

See https://guides.emberjs.com/v3.15.0/testing/testing-components/#toc_waiting-on-asynchronous-behavior it has a specific example for Ember debounce.

Took me a while to find this :).

like image 44
gellybutton Avatar answered Oct 13 '22 00:10

gellybutton