如何在Jest中模拟Geolocation API错误函数和!navigator.geolocation大小写?

问题描述

我在React应用程序中使用Geolocation API,我想在Jest中对其进行测试。这是我在应用程序中的Geolocation功能:

const getGeolocation = () => {
    const success = position => {
        const {latitude} = position.coords
        const {longitude} = position.coords

        // eslint-disable-next-line no-magic-numbers
        map.current.setView([latitude,longitude],12)
    }

    const error = () => {
        // eslint-disable-next-line no-magic-numbers
        map.current.setView([46.378333,13.836667],12)
    }

    if (!navigator.geolocation) {
        // eslint-disable-next-line no-magic-numbers
        map.current.setView([46.378333,12)
    } else {
        navigator.geolocation.getCurrentPosition(success,error)
    }
}

我能够测试success函数,但是我无法达到error函数,并且也无法模拟!navigator.geolocation情况。这是我的模拟:

const mockGeolocation = {
    getCurrentPosition: jest.fn()
        .mockImplementationOnce(success => Promise.resolve(success({
            coords: {
                latitude: 46.378333,longitude: 13.836667,},}))),watchPosition: jest.fn(),}

global.navigator.geolocation = mockGeolocation

如何模拟error函数和!navigator.geolocation的大小写?

解决方法

你可以像这样模拟它:

const mockGeolocation = {
    getCurrentPosition: jest.fn()
        .mockImplementationOnce((success,error) => Promise.resolve(error({
            code: 1,message: 'GeoLocation Error',}))),watchPosition: jest.fn(),}

global.navigator.geolocation = mockGeolocation

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...