I have the following code inside my useEffect. This code works fine.
Even tested the functionality via mocking and tests are fine too.
But in terms of coverage, it keeps coming up that the following 2 lines are not covered.
const check = async () => isValid();
check().then((result) => setValid(result));
When I try debug with breakpoints, I do hit these lines. The isValid function is being imported.
That is being tested elsewhere thus I am just mocking the outcome from the useState calls.
There is a mandatory 100% code coverage on this project I can't bypass.
Please advice how I could code cover this. Thanks.
P.S: Note that I am using following mock/spy. Without this, setCookie call loses coverage too.
jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f());
The component being tested
import React from 'react';
import Cookies from 'js-cookie';
import isValid from '../helpers/isValid';
import A from './A';
import B from './B';
import C from './C';
function AComponent() {
return (createComponent());
}
export const createComponent = ({data}) => {
const [valid, setValid] = React.useState(false);
const [cookie, setCookie] = React.useState(undefined);
React.useEffect(() => {
if (data) {
const check = async () => isValid(); // code coverage missing
check().then((result) => setValid(result)); // code coverage missing
}
setCookie(!!Cookies.get('my-cookie')); // no issue with code coverage
}, []);
if (cookie) {
return <A/>;
} else if (valid) {
return <B/>;
}
return <C/>;
};
export default AComponent;
These are the tests. The snapshot is as expected showing the 3 different outcomes.
Thus the mocking does work.
Thus looking to see how I could cover those lines even if I need to write a couple of tests
without mocking if theres a way.
jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f());
describe('Test', () => {
const render = (props) => shallow(
<AComponent
{...props}
/>
);
it('should render A', () => {
jest
.spyOn(React, 'useState')
.mockImplementationOnce(() => realUseState(false)) // mocks valid / setValid
.mockImplementationOnce(() => realUseState(true)); // mocks cookie / setCookie
const renderedModule = render({
data: {a: 1}
});
expect(renderedModule)).toMatchSnapshot();
});
it('should render B', () => {
jest
.spyOn(React, 'useState')
.mockImplementationOnce(() => realUseState(true)) // mocks valid / setValid
.mockImplementationOnce(() => realUseState(false)); // mocks cookie / setCookie
const renderedModule = render({
data: {a: 1}
});
expect(renderedModule)).toMatchSnapshot();
});
it('should render C', () => {
jest
.spyOn(React, 'useState')
.mockImplementationOnce(() => realUseState(false)) // mocks valid / setValid
.mockImplementationOnce(() => realUseState(false)); // mocks cookie / setCookie
const renderedModule = render({
data: {a: 1}
});
expect(renderedModule)).toMatchSnapshot();
});
}