Larney
Larney

Reputation: 1684

Jest React-native How to mock a function and return a response

I am new to Jest unit testing.

I want to test a component that makes multiple calls to the Geolocation getCurrentPosition() method.

For each call to the function I want to return a new coordinate object.

I have read various articles and tutorials but I am still struggling.

Any Ideas?

Upvotes: 2

Views: 1574

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110922

You can access the navigator object using global.navigator. So to mock getCurrentPosition just assign a jest.fn to it:

global.navigator = {
  getCurrentPosition : jest.fn()
}

So how to return new coordinates for every call. The easiest solution would be a global counter

const coords = [[1, 2], [2, 3]]
let counter = -1
global.navigator = {
  getCurrentPosition: jest.fn(() {
    counter++
    return coords[counter]
  })
}

Or you could use the calls property of the mock

const coords = [[1, 2], [2, 3]]
global.navigator = {
  getCurrentPosition: jest.fn(() =>
    coords[global.navigator.getCurrentPosition.mock.calls.length]
  )
}

Upvotes: 3

Related Questions