【问题标题】:Why is Window.location.search undefined even when Window.location.href includes a query string?即使 Window.location.href 包含查询字符串,为什么 Window.location.search 未定义?
【发布时间】:2020-05-15 12:29:37
【问题描述】:

我编写了一个函数来根据 David Walsh 的 Get Query String Parameters 获取给定查询字符串的值。

export const getQueryStringValue = (name) => {
  const formattedName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  const regex = new RegExp(`[\\?&]${formattedName}=([^&#]*)`);
  const results = regex.exec(window.location.search);

  return results === null
    ? ''
    : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

我已经为基于How to mock window.location.href with Jest + Vuejs?的函数编写了一个测试。

it('should return query string value', () => {
  global.window = Object.create(window);
  Object.defineProperty(window, 'location', {
    value: {
      href: 'http://dummy.com?foo=bar'
    }
  });

  expect(getQueryStringValue('foo')).toBe('bar');
});

但是,当我运行测试时,出现以下错误。

expect(received).toBe(expected) // Object.is equality

Expected: "bar"
Received: ""

当我控制台日志window.location.search 它返回undefined

  console.log __tests__/getQueryStringValue.test.js:14
    undefined

为什么即使 Window.location.href 包含查询字符串 (?foo=bar),Window.location 搜索也会返回 undefined?设置href还不够吗?

【问题讨论】:

  • 可能是因为define属性中的值是一个只有href的对象,所以search属性是未定义的
  • @HaibraynGonzález 这是有道理的。这让我想知道:当页面加载时,浏览器如何设置window.location.search
  • 为什么会失败?你的模拟是错误的。您只是设置href,它不会自动设置其他位置方法。

标签: javascript jestjs jsdom


【解决方案1】:

当您设置 Window.location href 因为jsdom does not currently handle navigation 时,不会自动模拟 Window.location 搜索。您有几个选项可以解决该错误。

选项 1:设置 Window.location 搜索

it('should return query string value', () => {
  global.window = Object.create(window);
  Object.defineProperty(window, 'location', {
    value: {
      search: '?foo=bar'
    }
  });

  expect(getQueryStringValue('foo')).toBe('bar');
});

选项 2:将 Window.location 设置为新的 URL 实例

it('should return query string value', () => {
  global.window = Object.create(window);
  Object.defineProperty(window, 'location', {
    value: new URL('http://dummy.com/?foo=bar')
  });

  expect(getQueryStringValue('foo')).toBe('bar');
});

来源:https://stackoverflow.com/a/59979453/11809808

【讨论】:

  • “我不知道为什么”,因为它没有被嘲笑......你不会免费获得所有的属性。
  • @epascarello “因为它没有被嘲笑......你不会免费获得所有的属性”。这回答了我的问题。我已经相应地更新了我的答案。
  • 我在那里发布了一个可以帮助你的答案:stackoverflow.com/a/59979453/3702797
  • @Kaiido 我已经根据您的链接更新了我的答案。感谢您提供该答案。我实际上更喜欢它而不是我原来的答案。
猜你喜欢
  • 1970-01-01
  • 2012-06-03
  • 2022-11-12
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2011-02-05
  • 1970-01-01
相关资源
最近更新 更多