How should I unit test my code-Part 2

Examples for testing the React, Redux code using Jest, and Enzyme.

Image result for testing
Image source: hackernoon

Getting Started

git clone https://github.com/anuk79/UnitTestingReactUsingJestAndEnzyme.git

Example 1: Testing React Component

// loading-spinner.jsximport React from 'react';const LoadingSpinner = (props) => {return (
<div className={props.customClassName}>
{'...loading'}
</div>
);
}
export default LoadingSpinner;
// loading-spinner.test.jsconst wrapper = shallow(<LoadingSpinner customClassName="test-  class"/>);expect(shallowToJson(wrapper)).toMatchSnapshot();
expect(wrapper.find('div').length).toBe(1);
expect(wrapper.find('div').text()).toBe('...loading');
expect(wrapper.find('div').prop('className')).toBe('test-class');

Example 2: Testing event handlers

const InputComponent = (props: Props) => {
return (
<input type={props.type} value={props.value} onChange={event => props.handleChange(event)} />
)
}
const handleChangeMock = jest.fn();const wrapper = shallow(<InputComponent handleChange={handleChangeMock}/>);
wrapper.find('input').simulate('change', 'testEvent');
expect(handleChangeMock).toBeCalledWith('testEvent');
wrapper.find('input').simulate('change', 'testEvent');

Example 3: Testing asynchronous calls

// user.resolver.jsexport const getUserDetails = async () => {
try {
const response = await fetch('/api/get-user-details',
{
'method': 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'accept': 'application/json'
}
}
);

if (!response.ok) {
throw new Error(response.status);
} else {
return response.json();
}
} catch (error) {
throw new Error(error);
}
}
// user.resolver.test.jsimport { getUserDetails } from './user.resolver';describe('User resolver', () => {
it('should return result when api call for userDetails succeeds', async () => {
const mockResult = { response: 'test response' }; window.fetch = jest.fn().mockImplementation(() => ({
ok: true,
status: 200,
response: 'test response',
json: () => new Promise(resolve => { resolve(mockResult); })
})); const userDetails = await getUserDetails(); expect(userDetails.response).toEqual('test response');});
it('should throw error when api call for userDetails fails', async () => {
window.fetch = jest.fn().mockImplementation(() => ({
ok: false,
status: 404
}));
try {
await getUserDetails();
} catch (e) {
expect(e.message).toEqual('Error: 404');
}
});
});

Tech enthusiast, Frontend Developer, Accessibility Advocate, MDE @Cloudinary. Creator of explore-a11y.netlify.app/ My motto — ‘Choose RIGHT over easy, always!’