2017-04-19 70 views
1
設置window.location的

我有一個無狀態的陣營組成部分,我想測試:不能得到,也不使用酶和玩笑

... 
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; 

我對這個文件的單元測試是目前如下:

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); 
    }); 
    }); 
}); 

是玩笑拋出我的錯誤是:

expect(received).toEqual(expected) 

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

我試圖印花襯裏在我的兩個COMPONE的不同部分nt和測試,並且它看起來像Jest/Enzyme不能訪問window對象。

我在做什麼錯?

回答

1

您必須在測試中使用global而不是window

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