为什么 Window.location.search 未定义,即使 Window.location.href 包含查询字符串?

Why is Window.location.search undefined even when Window.location.href includes a query string?

我根据 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, ' '));
};

我已经根据 .

编写了函数测试
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 它 returns undefined.

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

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

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

选项 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');
});

来源: