简体   繁体   English

如何使用带有自定义React钩子的选项对象模式

[英]How to use options object pattern with custom react hook

Consider the following custom fetch hook: 考虑以下自定义获取挂钩:

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;
};

I went to write tests for it like so: 我像这样去写测试:

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);
  });
});

The second test will fail because as far as I can tell it memoized the call with the first mock which doesn't return anything, meaning I get a "Cannot read property 'json' of undefined" error. 据我所知,第二项测试将失败,因为据我所知,它使用第一个不返回任何内容的模拟记忆了该调用,这意味着我收到“无法读取未定义的'json'属性'”错误。

Switching the hook to using positional arguments fixes the problem (as does disabling the first test). 将钩子切换为使用位置参数可解决此问题(与禁用第一个测试一样)。 Is there any way to make it work with the options object to simulate keyword arguments? 有什么方法可以使其与options对象一起使用以模拟关键字参数?

Actually, problem wasn't react at all: the test suite was reporting the failure in the wrong test. 实际上,问题根本没有反应:测试套件在错误的测试中报告了失败。 Took lots of console.log debugging, but got it done. 进行了许多console.log调试,但已完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM