Like the "layout" of a .geolocation navigator in a React Jest Test

I am trying to write tests for a reactive component that I created that uses navigator.geolocation.getCurrentPosition()in a method like this (a rough example of my component):

class App extends Component {

  constructor() {
    ...
  }

  method() {
    navigator.geolocation.getCurrentPosition((position) => {
       ...code...
    }
  }

  render() {
    return(...)
  }

}

I am using a create-responsive application that includes a test:

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

This test failed by printing this in the console:

TypeError: Cannot read property 'getCurrentPosition' of undefined

I am new to React, but have little experience with Angular 1.x. Angular typically models (as part of the tests in beforeEach) functions, services, and global object methods such as navigator.geolocation.etc. I spent time studying this problem, and this piece of code is the closest I could come up with:

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

I put this in my test file for the application, but it had no effect.

"" ?

: , navigator.getCurrentPosition . , jest JSDOM , window. JSDOM navigator. . getCurrentPosition , App.

+12
5

, global.navigator , , , .

, global.navigator .

const mockGeolocation = {
  getCurrentPosition: jest.fn(),
  watchPosition: jest.fn()
};

global.navigator.geolocation = mockGeolocation;

src/setupTests.js, - https://create-react-app.dev/docs/running-tests#initializing-test-environment

+23

, , , , , , , .

mock: getCurrentPosition: jest.fn() undefined, - , :

const mockGeolocation = {
  getCurrentPosition: jest.fn()
    .mockImplementationOnce((success) => Promise.resolve(success({
      coords: {
        latitude: 51.1,
        longitude: 45.3
      }
    })))
};
global.navigator.geolocation = mockGeolocation;

create-

+9

setupFiles

// __mocks__/setup.js

jest.mock('Geolocation', () => {
  return {
    getCurrentPosition: jest.fn(),
    watchPosition: jest.fn(),
  }
});

package.json

"jest": {
  "preset": "react-native",
  "setupFiles": [
    "./__mocks__/setup.js"
  ]
}
+5

enzyme. :

import React from 'react'
import App from './App'
import {shallow} from 'enzyme'

it('renders without crashing', () => {
  const app = shallow(<App />)
  expect(app).toBeDefined()
});

enzyme react-addons-test-utils. . , , , . , - Enzyme README:

API jQuery API DOM.

0

- global.navigator, setupTests.js.

const mockGeolocation = {
  getCurrentPosition: jest.fn(),
  watchPosition: jest.fn(),
}
global.navigator = { geolocation: mockGeolocation }
0

Source: https://habr.com/ru/post/1673164/


All Articles