【问题标题】:Mocking URLSeachParams模拟 URLSearchParams
【发布时间】:2019-03-23 23:23:31
【问题描述】:

我们使用jest 进行模拟。 enzyme 用于在我们的应用程序中进行渲染。

在这里我试图模拟URLSearchParamsget 方法。

我尝试使用

jest.spyOn(URLSearchParams, 'get'); 

但它不起作用。

我的反应类如下所示

export default class Concepts extends React.Component {
  static getDerivedStateFromProps(props) {
  const searchParams = new URLSearchParams(props.search);
  return {
     keyword: searchParams.get('q')
   };
}

我的测试如下所示

it('should be able to change the state', () => {
  jest.spyOn(URLSearchParams, 'get');
  const wrapper = mount(
        <Concepts search="test" />
   );
});

这是正确的方法吗?还有其他方法吗?在此先感谢:)

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    您必须在 URLSearchParams.prototype 上模拟 get,例如:

    jest.spyOn(URLSearchParams.prototype, 'get').mockImplementation((key) => key);
    

    【讨论】:

      【解决方案2】:

      这是我模拟URLSearchParams的解决方案

      global.URLSearchParams = jest.fn(x => ({
        get: jest.fn(y => x.includes(y) ? 'url does contain get parameter' : 'url does not contain get parameter'),
      }));
      

      【讨论】:

        【解决方案3】:

        试试这个!

        jest.spyOn(URLSearchParams.prototype, "get").mockReturnValue("some value");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-01
          • 2022-11-22
          • 2021-11-10
          • 2022-11-23
          • 2020-10-18
          • 2020-11-15
          • 2020-12-21
          • 1970-01-01
          相关资源
          最近更新 更多