使用Jest进行本机测试无法模拟Geolocation

时间:2018-03-20 13:25:54

标签: testing react-native geolocation jestjs

我试图在网络上找到一个解决方案,我发现了Stackoverflow answer,我按照说明操作但是我被阻止了:

TypeError: Cannot set property 'geolocation' of undefined

所以当我删除解决方案时,我的错误是:

ReferenceError: navigator is not defined

我的package.json看起来像这样:

  "dependencies": {
    "eslint-plugin-react-native": "^3.2.0",
    "prop-types": "^15.6.0",
    "react": "16.0.0",
    "react-native": "0.51.0",
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.1.2",
    "babel-jest": "^22.4.1",
    "babel-preset-react-native": "4.0.0",
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "eslint": "^4.14.0",
    "eslint-plugin-react": "^7.5.1",
    "jest": "^22.4.2",
    "jest-enzyme": "^6.0.0",
    "react-dom": "^16.2.0",
    "react-scripts": "^1.1.1",
    "react-test-renderer": "16.0.0-beta.5"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-navigation)"
    ],
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetsTransformer.js",
      "\\.(css|less)$": "<rootDir>/assetsTransformer.js"
    },
    "verbose": true
  },
  "plugins": [
    "react",
    "react-native"
  ],
  "ecmaFeatures": {
    "jsx": true
  },
  "env": {
    "react-native/react-native": true
  }

我的测试只是:

test('Map Component', () => {
  // create the snapshot
  const tree = renderer.create(<Map/>).toJSON();
  // test the snapshot
  expect(tree).toMatchSnapshot();
});

错误出现在navigator

上的这一行
navigator.geolocation.getCurrentPosition((position) => {

目前我没有使用导航器测试我的组件。我希望你们中的一些人有解决方案。

1 个答案:

答案 0 :(得分:1)

将此添加到您的笑话setup.js中:

global.navigator = {
  geolocation: {
    clearWatch: jest.fn(),
    getCurrentPosition: jest.fn((success, failure, options) => {
      success({
        coords: {
          longitude: 60,
          latitude: 60,
        },
      });
    }),
    stopObserving: jest.fn(),
    watchPosition: jest.fn(),
  },
};

setup.js文件是您在package.json文件中指定的文件。即:

"jest": {
  "setupFiles": [
    "<rootDir>/__tests__/setup.js"
  ],
  ...