I have the following implementation where upon clicking a button, some text is added to clipboard.
After a 5 second period state is changed and user can click the button again to copy.
The logic is working fine and written the test where I have 100% line coverage.
But not meeting branch and statement coverage. After investigating issue is due to this line.
setTimeout(() => setCopyStatus(''), 5000);
If I comment this out just to test, I get 100% test coverage for all.
Since I have met the line coverage. Unable to understand what I should do here to meet the coverage expectations.
Could I get some advice on how to target this to write a test to get the branch coverage.
This is the component.
import React, { useState } from 'react';
import { Button } from '../../Button';
const A = ({
text,
}) => {
const [copyStatus, setCopyStatus] = useState('');
const sleep = () => {
// issue is with this line. If I comment this out, I get full coverage.
setTimeout(() => setCopyStatus(''), 5000);
};
const onClick = () => {
window.navigator.clipboard.writeText(text)
.then(() => {
setCopyStatus('yes');
sleep();
})
.catch(() => setCopyStatus('no'));
};
const CopyBtn = () => (
<Button onClick={onClick}>
Click
</Button>
);
return (<div>
{CopyBtn}
</div>);
};
export default A;
This is the current test which all passes and but as mentioned not meeting branch coverage.
import React from 'react';
import { mount } from 'enzyme';
import A from '../../../src/components/A';
jest.mock('../../Button', () => ({
Button: 'button',
}));
describe('A component test', () => {
const props = {
text: 'mock',
};
it('should copy to clipboard as expected', () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: jest.fn().mockReturnValueOnce(Promise.resolve()),
},
});
const renderedModule = mount(<A {...props} />);
renderedModule.find('button').simulate('click');
expect(navigator.clipboard.writeText).toBeCalledTimes(1);
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('expectedCopy');
});
it('should throw error on attempt to copy to clipboard', () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: jest.fn().mockRejectedValue(new Error()),
},
});
const renderedModule = mount(<CopyLink {...props} />);
renderedModule.find('button').simulate('click');
expect(navigator.clipboard.writeText).toBeCalledTimes(1);
expect(renderedModule.find('div.error').at(0).exists()).toBeTruthy();
});
// some other tests where I try without text value other redux tests not related to issue.
});