Michael Porter
Michael Porter

Reputation: 229

Jest, Enzyme test failing on window variable undefined

I'm trying to create a window object to pass to my tests that includes a window variable. The test looks like:

const baseProps = {};

Enzyme.configure({ adapter: new Adapter() });

const baseWrapper = shallow(
  <DivisionOrderIndex {...baseProps} />,
);

describe('<DivisionOrderIndex />', () => {
  test('renders the MsDataGridServer', () => {
    expect(baseWrapper.find(MsDataGridBulkDelete))
      .toHaveLength(1);
  });

The error message I receive is:

TypeError: Cannot read property 'read_only' of undefined

      300 |             </TitleButton>
      301 |           </div>
    > 302 |           {!window.jsdata.read_only && (
          |                           ^
      303 |             <div id="page-buttons">
      304 |               <a href="/division_order_create" className="btn btn-primary">Create New</a>
      305 |             </div>

I've tried adding that data to my window object like so:

describe('<DivisionOrderIndex />', () => {
  Object.defineProperty(window, 'jsdata', {
      read_only: false,
    });
  test('renders the MsDataGridServer', () => {
    expect(baseWrapper.find(MsDataGridBulkDelete))
      .toHaveLength(1);
  });

But I continue to get the same error. Is this the correct way to pass both the window object or the variables? Any input would be appreciated.

Upvotes: 0

Views: 584

Answers (1)

rzwnahmd
rzwnahmd

Reputation: 1082

That's not how you add a property to an object. What you're doing here is adding a descriptor property that describes your object, there are only a few of them that you can set here e.g. writable, configurable etc.

You need to mock window object in the setupTests.js file like this:

window.jsdata = {
  read_only: false
}

Upvotes: 2

Related Questions