单元测试 navigator.permissions.query({ name: 'geolocation' }) using Jest (React)

问题描述 投票:0回答:1

我试着模拟这个功能

const location = window.navigator && window.navigator.geolocation;
if (location) {
  location.getCurrentPosition(
    (position) => {
      handleChangeLocation(position.coords.latitude, position.coords.longitude);
    },
    (error) => {
      console.log(error);
    },
  );
}
navigator.permissions
  .query({ name: 'geolocation' })
  .then((permission) => {
    permission.onchange = function () {
      if (permission.state === 'granted') {
        location.getCurrentPosition((position) => {
          handleChangeLocation(position.coords.latitude, position.coords.longitude);
        });
      } else if (permission.state === 'denied') {
        // Todo
      }
    };
  });

到目前为止,我试过在setupTest.js处创建全局导航仪。

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

但最后还是出现了错误

enter image description here

我试图通过添加jest.spyOn(window.navigator.permissions.query({ name: 'geolocation' }), 'onchange', 'get').mockReturnValueOnce('granted');但我认为有一些错误,因为它说未定义。

reactjs unit-testing jestjs enzyme
1个回答
0
投票

该错误意味着 navigator.permissions 是未定义的。Jest使用JSDOM来模拟Node.js环境下的真实DOM,并且没有很多浏览器会有的API。

所有缺失的globals都需要手动存根。

navigator.permissions = { query: jest.fn() };
navigator.geolocation = { getCurrentPosition: jest.fn() };
© www.soinside.com 2019 - 2024. All rights reserved.