Richard Kho
Richard Kho

Reputation: 5286

Cannot Get nor Set window.location using Enzyme and Jest

I've got a stateless React component that I would like to test:

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

My unit test for this file is currently as follows:

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

The error that Jest throws me is:

expect(received).toEqual(expected)

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

I tried print lining at different parts of both my component and test, and it looks like Jest/Enzyme isn't able to access the window object.

What am I doing wrong?

Upvotes: 3

Views: 2757

Answers (1)

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110892

You have to use global instead of window in your test.

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

Upvotes: 2

Related Questions