Mocha Tests for Focus-Related Behavior (Backbone / CoffeeScript Application)

I have a Backbone application written in CoffeeScript. I am trying to use Mocha (with Chai and Sinon) to write tests for DOM-related behavior, but it seems that hidden fixtures (I use js-fixtures now, but I also tried it unsuccessfully with a hidden '#fixtures'div) do not log specific behaviors, related to the DOM, which makes it impossible to test certain types of behavior related to the DOM (apparently).

For example, in my main application view, there are several subqueries that are never displayed at the same time: when the view application displays subview A, it remembers the focused element of the currently active subview B ( @_visibleView), saves this information to subview B, closes subview B and then displays subview A.

    _rememberFocusedElement: ->
      focusedElement = $ document.activeElement
      if focusedElement
        focusedElementId = focusedElement.attr 'id'
        if focusedElementId
          @_visibleView?.focusedElementId = focusedElementId

This works when I test it manually, but when I try to write unit tests for this behavior, they fail because I cannot set the focus (for example, through $(selector).focus()) to an element in a hidden div / iframe. (I have the same issue with functionality that listens for window resize events.)

I thought that if I changed $ document.activeElementto @$ ':focus", I could get different results, but this does not fix the problem.

Mocha (BDD). TEXTAREA , undefined, , id = '', .

    beforeEach (done) ->
      fixtures.path = 'fixtures'
      callback = =>
        @$fixture = fixtures.window().$ "<div id='js-fixtures-fixture'></div>"
        @appView = new AppView el: @$fixture
        done()

    describe 'GUI stuff', ->
      it 'remembers the currently focused element of a subview', (done) ->
        @appView.mainMenuView.once 'request:formAdd', =>
          @appView._visibleView.$('#transcription').focus()
          console.log @appView._visibleView.$('#transcription').prop 'tagName'
          console.log @appView._visibleView.$(':focus').prop 'tagName'
          done()
        @appView.mainMenuView.trigger 'request:formAdd'

, ?

+4
1

, - : "unit test" . " , unit test (, Mocha)". "unit test", , : , ( JS , ).

, , unit test , . A unit test - , () DOM, .

, handleFocus ( ). , JavaScript, CoffeScript :

describe('#handleFocus', function() {
    it('remembers the currently focused element of a subview', function() {
        var setFocusStub = sinon.stub($.fn, 'focus');
        appView._visibleView.handleFocus();
        expect(setFocusStub.calledOnce).to.be(true);
    });
});

, , , . , , , DOM ( ) X; , , X. , , , , "X" , DOM.

, , : ", , , ?" , (, ) . , , , .

, , , , , .

+1

All Articles