React Native: Simulate offline device in Jest unit test

前端 未结 1 999
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 23:46

I\'m writing a React Native app and I\'m using Jest to unit test my code.

I\'ve written a function than checks if there is an internet connection. I know want to wri

相关标签:
1条回答
  • 2021-01-19 00:14

    This is pretty simple, just mock the NetInfo like so:

    import {
        NetInfo
    } from "react-native";
    import checkNetwork from "...";
    import {
        NO_NETWORK_CONNECTION
    } from "...";
    
    jest.mock('react-native', () => ({
        NetInfo: {
            isConnected: {
                fetch: jest.fn()
            }
        }
    }))
    
    test('test offline', async () => {
        NetInfo.isConnected.fetch.mockResolvedValueOnce(false)
        expect(await checkNetwork()).toBe(NO_NETWORK_CONNECTION)
    })
    
    test('test online', async () => {
        NetInfo.isConnected.fetch.mockResolvedValueOnce(true)
        expect(await checkNetwork()).toBe(true)
    })
    
    0 讨论(0)
提交回复
热议问题