1

我正在尝试为以下代码编写单元测试用例。但是,我无法实现 100% 的测试覆盖率。

我正在使用@react-native-community/netinfo包来获取网络连接信息和@testing-library/react-native编写单元测试用例。

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>
    )
}

应用测试.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**
4

0 回答 0