在 RN 中模拟导航器以进行单元测试

Mocking navigator in RN for unit tests

对于我的测试,我使用 mochaenzymesinon 进行存根,chai 进行断言,mockery 进行模拟模块。

现在模拟导航器进行地理定位的最佳机制是什么。我尝试从 https://github.com/jhnns/rewire rewire 注入我的 sinon stubed 导航器。这对我有用,但设置存根感觉很麻烦。 我喜欢 https://github.com/2gis/mock-geolocation 因为它感觉更自然的嘲笑方式。但不幸的是我无法使用它,因为它使用 window 变量。

我尝试像

一样使用 mocha-jsdom
import jsdom from 'mocha-jsdom';
jsdom();
const geolocate = require('mock-geolocation');

但是我收到了类似

的错误
/..../node_modules/mock-geolocation/src/geolocate.js:225
})(window, navigator);
   ^

ReferenceError: window is not defined
    at Object.<anonymous> (/like

/..../node_modules/mock-geolocation/src/geolocate.js:225:4)
    at Module._compile (module.js:409:26)

我运行我的测试是这样的mocha --require react-native-mock/mock --compilers js:babel-register --recursive

我用的是 this.jsdom = require('jsdom-global')() 而不是 mocha-jsdom 这似乎解决了问题。