unit-testing - 如何在 React Jest 测试中获取 "mock"navigator.geolocation

标签 unit-testing reactjs jestjs create-react-app

我正在尝试为我构建的 react 组件编写测试,该组件在这样的方法中利用 navigator.geolocation.getCurrentPosition() (我的组件的粗略示例):

class App extends Component {

  constructor() {
    ...
  }

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

  render() {
    return(...)
  }

}

我正在使用create-react-app ,其中包括一个测试:

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

此测试失败,在控制台中打印出以下内容:

TypeError: Cannot read property 'getCurrentPosition' of undefined

我是 React 新手,但对 Angular 1.x 有相当多的经验。在 Angular 中,通常会模拟(在 beforeEach 的测试中)函数、“服务”和全局对象方法,例如 navigator.geolocation.etc。我花了时间研究这个问题,这段代码是我能得到的最接近模拟的代码:

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

我把它放在我的App测试文件中,但没有效果。

如何“模拟”此导航器方法并让测试通过?

编辑:我研究了使用一个名为 geolocation 的库据说它包装了 navigator.getCurrentPosition 以在节点环境中使用。如果我理解正确的话,jest 在节点环境中运行测试并使用 JSDOM 来模拟诸如 window 之类的东西。我还没有找到太多关于 JSDOM 支持 navigator 的信息。上面提到的库在我的 react 应用程序中不起作用。即使库本身已正确导入并且在 App 类的上下文中可用,使用特定方法 getCurrentPosition 也只会返回 undefined。

最佳答案

似乎已经有一个 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

关于unit-testing - 如何在 React Jest 测试中获取 "mock"navigator.geolocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008925/

相关文章:

css - 标题 : Creating an infinite logo slider using React and CSS without third-party libraries

javascript - 使用 Javascript 获取 HTML 元素样式

javascript - 如何重置测试之间导入的模块

jestjs - 在 Jest 中测试 ScrollIntoView

unit-testing - 在进程中设置 "late"测试用例的最佳方法

visual-studio-2010 - 为什么VS2010不把/bin/debug中的所有DLL都复制到单元测试目录下?

java - void 方法应使用哪个测试替身

c# - 可以模拟自定义属性 c# 吗?

javascript - react - JavaScript : How to properly position a dropdown menu on top of a Google Map

javascript - Enzyme/Jest 静态方法模拟未运行