Reactjs 模拟URLSeachParams

Reactjs 模拟URLSeachParams,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我们正在使用jest进行模拟酶用于在我们的应用程序中进行渲染 这里我试图模拟URLSearchParams的get方法 我试着用 jest.spyOn(URLSearchParams, 'get'); 但它不起作用 我的班级看起来像贝娄 export default class Concepts extends React.Component { static getDerivedStateFromProps(props) { const searchParams = new URL

我们正在使用
jest
进行模拟<代码>酶用于在我们的应用程序中进行渲染

这里我试图模拟
URLSearchParams
get
方法

我试着用

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" />
   );
});
it('应该能够更改状态',()=>{
jest.spyOn(URLSearchParams,'get');
常量包装器=装入(
);
});

这是正确的方法吗?还有其他方法吗?提前感谢:)

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

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

这是我对mock的解决方案

试试这个

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

谢谢,工作很好!
jest.spyOn(URLSearchParams.prototype, "get").mockReturnValue("some value");