2017-04-19 5 views
1

Ich habe eine stateless Komponente Reagieren, die ich zu testen möchte:Can not Get noch Set window.location mit Enzym und Jest

... 
function NavigationLink() { 
    var _href = '#' + AppConstants.PERSONAL_INFORMATION_SECTION; 
    var firstElementToFocus = AppConstants.FIRST_NAME_ID; 

    function _onClick (event) { 
    event.preventDefault(); 
    window.location = _href; 
    document.getElementById(firstElementToFocus).focus(); 
    } 

    return (
    <div> 
     <a href={_href} id="skip-nav" onClick={_onClick} >{'Skip to main content'}</a> 
    </div> 
); 
} 

module.exports = NavigationLink; 

für diese Datei My Unit-Test ist zur Zeit wie folgt:

jest.dontMock('../NavigationLink.react.js'); 

var React = require('react'); 
var enzyme = require('enzyme'); 
var shallow = enzyme.shallow; 
var wrapper; 

var AppConstants = require('../../constants/AppConstants'); 
var ProductStore = require('../../stores/ProductStore'); 
var NavigationLink = require('../NavigationLink.react.js'); 

var mockPreventDefault = jest.fn(); 

describe('NavigationLink', function() { 
    describe('when the user is on a consumer application', function() { 
    beforeEach(function setup() { 
     var fieldToFocus = AppConstants.FIRST_NAME_ID; 

     document.getElementById = function (mockData) { 
     return { 
      focus: function() { 
      return true; 
      } 
     } 
     } 

     ProductStore.getProductDetailsState.mockReturnValue({ 
     ... 
     }); 


     wrapper = shallow(
     <NavigationLink /> 
    ); 
    }); 

    it('sets the window location to the Personal Information Section when the skip navigation link is selected by the user', function() { 
     wrapper.find('#skip-nav').simulate('click', { preventDefault: mockPreventDefault }); 
     expect(window.location.hash).toEqual('#' + AppConstants.PERSONAL_INFORMATION_SECTION); 
    }); 
    }); 
}); 

der Fehler, der Jest mir wirft, ist:

expect(received).toEqual(expected) 

Expected value to equal: 
    "#formBody" 
Received: 
    "" 

ich beide Druck Futter an verschiedenen Teilen meines compone versucht nt und test, und es sieht so aus, als ob Jest/Enzyme nicht auf das Objekt window zugreifen kann.

Was mache ich falsch?

Antwort

1

Sie müssen global anstelle von window in Ihrem Test verwenden.

expect(global.location.hash).toEqual('#' + AppConstants.PERSONAL_INFORMATION_SECTION);