How to mock different hooks in ReactJS?
Writing testing cases is always good to make a robust application. In ReactJS, writing test cases are quite easy and interesting. In any language, mocking different items are very common.
In ReactJS we can mock different hooks, window objects, document cookies, and document objects very easily.
How to mock window object?
Following is the App.test.js file code:
import React from 'react'; import { shallow } from 'enzyme'; import App from './App'; describe('Application home page test cases', () => { let windowSpy; beforeEach(() => { windowSpy = jest.spyOn(global, 'window', 'get'); windowSpy.mockImplementation(() => ({ env: jest.fn() })); }); afterEach(() => { windowSpy.mockRestore(); }); it('Mock window object', () => { const wrapper = shallow(<App/>); expect(wrapper.find('div.set-title').text()).toBe('React Application'); }); });
Following is the code for App.js:
import React from 'react'; import './App.css'; function App() { const env = window.env.domain; return ( <div> <div className="set-title">React Application</div> </div> ); } export default App;