用URL对象进行笑话测试

时间:2020-03-23 19:32:33

标签: reactjs testing url mocking jestjs

在某些情况下,我的代码使用的是这样创建的URL api:

const _url = new URL(window.location.href);

并按如下方式使用:

if (_url.searchParams.get('locale')) {
    do something
}

但是在玩笑测试中,我得到一个错误:

TypeError: Cannot read property 'get' of undefined

我已经在安装文件中尝试进行全局模拟:

global.URL = jest.fn(() => {
  return {
    searchParams: jest.fn(() => {
      return {
        get: jest.fn(() => {
          return '';
        }),
      };
    }),
  };
});

但是它似乎不起作用。查看我的_url对象在控制台上记录的输出,看起来好像一起都缺少searchParam属性:

URL {
  [Symbol(impl)]: URLImpl {
    _url: {
      scheme: 'http',
      username: '',
      password: '',
      host: 'localhost',
      port: null,
      path: [Array],
      query: null,
      fragment: null,
      cannotBeABaseURL: false
    },
    [Symbol(wrapper)]: [Circular]
  }
}

我在做什么错了?

2 个答案:

答案 0 :(得分:0)

我能够通过在设置文件中进行全局模拟来解决此问题:

global.URL = (() => {
  return {
    searchParams: {
      get: jest.fn((param) => {
        const reg = `[?&]${param}=([^&]*)`;
        return (window.location.search.match(reg) && window.location.search.match(reg)[1]) ? window.location.search.match(reg)[1] : '';
      }),
    },
  };
});

答案 1 :(得分:0)

为避免单元测试错误,可以将try {} catch(e) {}块与默认值一起使用,如下所示:

    const myFunction = url => {
        try {
            return new URL(url).hostname;
        } catch (e) {
            console.warn('new URL(...) object is not supported');
        }
        return {};
    }