模拟navigator.geolocation.getCurrentPosition时发生不变冲突错误

时间:2018-10-18 13:15:16

标签: react-native geolocation mocking jestjs navigator

尝试测试在react-native中使用IL __tests__/accessMgr.test.js ● Test suite failed to run Invariant Violation: Native module cannot be null. at invariant (node_modules/fbjs/lib/invariant.js:44:15) at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1) at Object.<anonymous> (node_modules/react-native/Libraries/Geolocation/Geolocation.js:21:26) at node_modules/react-native/Libraries/Core/InitializeCore.js:196:58 at Object.getValue [as geolocation] (node_modules/react-native/Libraries/Utilities/defineLazyObjectProperty.js:44:10) at Object.<anonymous> (src/tools/accessmgr/geo.js:5:41) 的库。

错误:

const { geolocation: { getCurrentPosition } } = navigator;

给出错误的行:

import AccessMgr from '../src/tools/accessmgr/accessmgr';

const P = Promise;
const mockFn = jest.fn().mockImplementation;
const coords = {
  coords: {
    latitude: 51.1,
    longitude: 45.3,
  },
};

const mockGeolocation = {
  getCurrentPosition: mockFn(yeah => P.resolve(yeah(coords))),
};

navigator.geolocation = mockGeolocation;

test('isDeviceReady returns true if all services has access granted', () => {
  const accessMgr = new AccessMgr({
    photobook: true,
    geo: true,
    push: true,
  });

  expect(accessMgr.isDeviceReady()).toBeTruthy();
});

测试:

let schema = Joi.object().keys({
  personal_info: Joi.object().keys({
    first_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
    last_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
    phone: Joi.string().min(10).max(10).regex(Regex.num, 'num').required().error(JoiCustomErrors),
    nickname: Joi.string().min(3).max(12).regex(Regex.alphanum, 'alphanum').required().error(JoiCustomErrors),
    birthday: Joi.date().max(`01-01-${new Date().getFullYear()-8}`).required().error(JoiCustomErrors),
    IDNumber: Joi.string().min(9).max(9).regex(Regex.num, 'num').required().error(JoiCustomErrors),
    address: Joi.object().keys({
      city: Joi.string().valid(Cities).required().error(JoiCustomErrors),
      street: Joi.string().min(2).max(15).regex(Regex.alphabeta, 'alphabeta').required().error(JoiCustomErrors),
      house_number: Joi.string().min(1).max(5).regex(Regex.alphanum, 'alphanum').error(JoiCustomErrors)
    })
  }),
  permission_level: Joi.number().min(1).max(9).required().error(JoiCustomErrors)
});
Joi.validate(req.body, schema, { abortEarly: false }, (err) => {
  if (err) return cast.joiError(err);
  return create_employee(result);
});

0 个答案:

没有答案