Unable to achieve 100% test coverage using @react-native-community/netinfo

505 Views Asked by At

I am trying to write unit test cases for the below code. However, I am not able to achieve 100% test-coverage.

I am using @react-native-community/netinfo package to get the network connection information and @testing-library/react-native for writing unit test cases.

const App = () => {
    const [isInternetReachable, setIsInternatReachable] = useState(false)
    const [icon, setIcon] = useState("network-strength-off")

    const getNetworkIcon = (reachable) => {
        if(!reachable){
            return "network-strength-off"
        }else{
            return "network-strength-4"
        }
    }

    useEffect(() => {
        NetInfo.addEventListener(state => {
            setIsInternatReachable(state.isInternetReachable)
            setIcon(getNetworkIcon(state.isInternetReachable))
        })
    },[])

    return (
        <View>
            <MaterialCommunityIcons name={icon} size={100} />
            <Text>Is Internet Reachable? {isInternetReachable}</Text>
        </View>
    )
}

App-test.js

import {render} from "@testing-library/react-native";
import {addEventListener} from "@react-native-community/netinfo";

describe('Net Info', () => {
    jest.mock('@react-native-community/netinfo', () => {
        addEventListener: jest.fn()
    });

    it('Happy Path Test', () => {
        addEventListener.mockResolvedValueOnce({type: 'test', isInternetReachable: false,})

        const {queryByText} = render(<App />);
        expect(queryByText(/Is Internet Reachable/i)).not.toBeNull()
    })
})
**Percentage Coverage : 58.33
Uncovered Line : 11- 15, 22-23**
0

There are 0 best solutions below