Reputation: 1697
I use the Geolocation API in a React app and I want to test it in Jest. This is my Geolocation function in the app:
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, 13.836667], 12)
} else {
navigator.geolocation.getCurrentPosition(success, error)
}
}
I'm able to test the success
function, but I can't reach the error
function and I also was not able to mock the !navigator.geolocation
case. This is my mock:
const mockGeolocation = {
getCurrentPosition: jest.fn()
.mockImplementationOnce(success => Promise.resolve(success({
coords: {
latitude: 46.378333,
longitude: 13.836667,
},
}))),
watchPosition: jest.fn(),
}
global.navigator.geolocation = mockGeolocation
How can I mock the error
function and the !navigator.geolocation
case?
Upvotes: 1
Views: 1933
Reputation: 6378
You can mock it like this:
const mockGeolocation = {
getCurrentPosition: jest.fn()
.mockImplementationOnce((success, error) => Promise.resolve(error({
code: 1,
message: 'GeoLocation Error',
}))),
watchPosition: jest.fn(),
}
global.navigator.geolocation = mockGeolocation
Upvotes: 2