首页 > 解决方案 > 创建 React 应用程序 - 如何在全局范围内模拟您自己的组件

问题描述

我有一个我想为我的测试模拟的组件,它存在于src/components/shared/DebouncedInput.js中,它看起来像这样:

import { useState, useCallback } from 'react'
import debounce from 'lodash.debounce'

const useDebounce = (callback, delay) => {
  const debouncedFn = useCallback(
    debounce((...args) => callback(...args), delay),
    [delay] // will recreate if delay changes
  );
  console.log('debouncedFn', debouncedFn);
  return debouncedFn;
};

function DebouncedInput(props) {
  const [value, setValue] = useState(props.value);
  const debouncedSave = useDebounce(
    (nextValue) => props.onChange(nextValue),
    props.delay
  );

  const handleChange = (nextValue) => {
    setValue(nextValue);
    debouncedSave(nextValue);
  };

  return props.renderProps({ onInputChange: handleChange, value });
};

export default DebouncedInput;

我在src/ mocks文件夹中也有第三方库的模拟。他们的模拟在我的测试中工作正常,但我不确定在哪里为我想要模拟的我自己的组件DebouncedInput放置一个模拟,以便它对我的测试全局可用:

import React from "react";

function DebouncedInput(props) {
  const handleChange = (nextValue) => props.onChange(nextValue);

  return props.renderProps({ onInputChange: handleChange, value: props.value });
};

export default DebouncedInput;

我已将它放在src/components/shared/ mocks /DebouncedInput.js文件夹中,但我的测试仍然是原始实现而不是模拟。我应该如何实现这个模拟?

标签: reactjsjestjsmocking

解决方案


推荐阅读