Javascript 如何将选项对象模式与自定义react挂钩一起使用

Javascript 如何将选项对象模式与自定义react挂钩一起使用,javascript,reactjs,enzyme,Javascript,Reactjs,Enzyme,考虑以下自定义获取挂钩: import { useEffect, useState } from 'react'; const useFetch = ({ url, request, initialData = {}, fetch = window.fetch.bind(window), }) => { const [data, update] = useState(initialData); const fetchData = async () => {

考虑以下自定义获取挂钩:

import { useEffect, useState } from 'react';

const useFetch = ({
  url,
  request,
  initialData = {},
  fetch = window.fetch.bind(window),
}) => {
  const [data, update] = useState(initialData);
  const fetchData = async () => {
    const resp = await fetch(request || url);
    const json = await resp.json();
    update(json);
  };

  fetchData();
  return data;
};
我是这样为它编写测试的:

const TestHook = ({ hook, args }) => {
  const res = hook(...args);
  return <div result={res} />;
};

let fakeFetch;
beforeEach(() => {
  fakeFetch = jest.fn();
});

describe('fakeFetch', () => {
  it('should use initialData when present', () => {
    const args = [{
      url: 'http://foo.com',
      initialData: 3,
      fetch: fakeFetch,
    }];

    const wrapper = mount(<TestHook hook={useFetch} args={args} />);
    const { result } = wrapper.find('div').props();
    expect(result).toBe(3);
  });

  it('should update with new data from the fetch', done => {
    fakeFetch.mockReturnValueOnce(fakeResponseFactory('foo'));
    const args = [{
      url: 'http://foo.com',
      intialData: 'baz',
      fetch: fakeFetch,
   } ];

    const wrapper = mount(<TestHook hook={useFetch} args={args} act={act}/>);
    const { result } = wrapper.find('div').props();
    expect(result).toEqual('baz');
    setTimeout(() => {
      act(() => wrapper.update());
      const { result } = wrapper.find('div').props();
      expect(result).toEqual('foo');
      done();
    }, 10);
  });
});
consttesthook=({hook,args})=>{
const res=钩子(…args);
返回;
};
让假货来取;
在每个之前(()=>{
fakeFetch=jest.fn();
});
描述('fakeFetch',()=>{
它('存在时应使用初始数据',()=>{
常量args=[{
网址:'http://foo.com',
初始数据:3,
fetch:fakeFetch,
}];
const wrapper=mount();
const{result}=wrapper.find('div').props();
期望(结果)toBe(3);
});
它('应使用提取的新数据进行更新',完成=>{
mockReturnValueOnce(fakerResponseFactory('foo');
常量args=[{
网址:'http://foo.com',
intialData:“baz”,
fetch:fakeFetch,
} ];
const wrapper=mount();
const{result}=wrapper.find('div').props();
期望(结果)。toEqual('baz');
设置超时(()=>{
act(()=>wrapper.update());
const{result}=wrapper.find('div').props();
期望(结果)。toEqual('foo');
完成();
}, 10);
});
});
第二个测试将失败,因为据我所知,它用第一个mock(不返回任何内容)记录了调用,这意味着我得到了一个“无法读取未定义的属性‘json’”错误


将钩子切换为使用位置参数修复了问题(禁用第一个测试也是如此)。有没有办法让options对象模拟关键字参数?

事实上,问题根本没有反应:测试套件在错误的测试中报告了失败。进行了大量的console.log调试,但完成了。

事实上,问题根本没有反应:测试套件在错误的测试中报告了失败。进行了大量console.log调试,但已完成