Mocking window with sinon, wet, enzyme and reaction

I am trying to make fun of the window object for the component that I am using with only the four libraries listed above.

I know that this can be done using JSDom, but the client does not use it. Based on my research, just executing sinon.stub (window, 'location') should work, but when I run my tests, I still get Window undefined in my component.

Currently, the component is called inside the return render {window.location.host}

some thoughts on what I'm doing wrong to make the sinon drown out this part. Once I complete this part, I can concentrate on testing other parts of this component that have nothing to do with the window.

My testing method:

import React from 'react'; import { shallow } from 'enzyme'; import chai from 'chai'; chai.should(); import sinon from 'sinon'; import BillingStatementRow from '../BillingStatementRow'; describe('Test <BillingStatementRow /> Component', function() { context('Function Testing', function() { it('Test - onFieldChange - Make sure it handles NaN', function() { var e = {target: {value: NaN}}; var window = { location : { host : "..." } }; var mockedOnChange = sinon.spy(); const wrapper = shallow ( <BillingStatementRow slds={''} key={'1'} Id={'1'} inputValue={'0'} salesInvoice={'SIN0001'} invoicedAmount={1000} duedate={'1461628800000'} outstandingBalance={1000} receiptRemaining={1000} amountAllocated={1000} onChange={mockedOnChange.bind(this,'BS0001')} /> ); wrapper.instance().onFieldChange('amountAllocated', e); wrapper.update(); }) }); }); 
+6
source share
1 answer

Sinon stubs / spies / mocks only work with functions. In this case, you are trying to make fun of a global (nested) variable for which Sinon is not a suitable tool.

Instead, as in the browser, you can create a global object that wears out the right amount of window to work with your component, which is easy because it only accesses window.location.host .

So, before creating a component, declare the following:

 global.window = { location : { host : 'example.com' } }; 
+17
source

All Articles