简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM