简体   繁体   English

测试组件使用自定义钩子 react-testing-library

[英]Test component use custom hook react-testing-library

I'm using react-testing-library for test my component using custom hook.我正在使用 react-testing-library 使用自定义钩子测试我的组件。 But I can't make it pass.但我不能让它过去。 Here is my code这是我的代码

function useInput<T>(): Return<T> {
    const [input, setInput] = useState<T>({} as T);
    const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);

    const handleInputChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setInput({
            ...input,
            [e.target.name]: e.target.value
        });
        setDirty({
            ...isDirty,
            [e.target.name]: true
        });
    };

    const resetInput = () => {
        Object.keys(input).map((v) => (input[v as keyof T] as unknown as string) = '');
        Object.keys(isDirty).map((v) => (isDirty[v as keyof T] as unknown as string) = '');
        setInput({...input});
        setDirty({...isDirty});
    };

    return [input, handleInputChange, isDirty, resetInput, setInput]
}

const Login: React.FC = () => {
    const [input, handleChangeInput, isDirty, resetInput] = useInput<IInput>();

    return (
                <input
                    value={input.username}
                    onChange={handleChangeInput}
                    name={'username'}
                    className={classNames(`shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline`)}
                    id={'username'} type={'text'} placeholder={'Username'}/>

    )
}

test测试

import React from "react";
import {render, unmountComponentAtNode} from "react-dom";
import Login from './index'
import {renderHook, act as actHook} from '@testing-library/react-hooks'
import {MemoryRouter} from "react-router-dom";
import {useInput} from '../hooks';
import { fireEvent } from '@testing-library/react';


describe('test login', () => {
  it('to match snapshot', () => {
    render(
      <MemoryRouter>
        <Login/>
      </MemoryRouter>
      ,
      container);
    expect(container).toMatchSnapshot()
  });

  it('input correct when change username',  () => { //can't pass
     render(
      <MemoryRouter>
        <Login/>
      </MemoryRouter>
      ,
      container);

    const {result} = renderHook(() => useInput());
    const [input, handleChangeInput] = result.current;
    const inputName = container.querySelector('#username');
    fireEvent.change(inputName, {target: {value: 'test'}});

    actHook(() => {
      handleChangeInput({target: {name: 'username', value: 'test'}});
    });
    expect(input).toBe({
      username: 'test'
    })

  })
});

My script test is.我的脚本测试是。 When input fireEvent call, input change value and value in hook useInput have same value.当输入 fireEvent 调用时,输入变化值和钩子 useInput 中的值具有相同的值。 But I can make it pass.但我可以让它过去。 Where is my wrong?我的错在哪里? Please help请帮忙

React hooks testing library was created to test hooks without having to mount it on test component. React hooks 测试库的创建是为了测试钩子,而无需将其安装在测试组件上。 You have to decide to either test the hook itself (without use of your Login component) or your component as whole - then you don't need hooks testing library at all - react-testing-library should be enough.您必须决定测试钩子本身(不使用您的登录组件)或整个组件-那么您根本不需要钩子测试库-react-testing-library 就足够了。 Your fireEvent actually "fire" your hook without the part below你的fireEvent实际上在没有下面的部分的情况下“触发”你的钩子

const {result} = renderHook(() => useInput());
const [input, handleChangeInput] = result.current;

暂无
暂无

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

相关问题 使用 test 和 react-testing-library 测试反应组件 - Test a react component using test and react-testing-library 使用 Redux 和 react-testing-library 测试 React 组件 - Test React Component using Redux and react-testing-library 如何使用 react-testing-library 测试材质 ui MenuList 组件上的按键按下事件 - How to test key down event on material ui MenuList component using react-testing-library 如何使用react-testing-library中的“ wait”测试不能处理拒绝承诺的组件? - How to test a component that does not handle a rejected promise with `wait` from the react-testing-library? 使用 react-testing-library 时如何测试组件是否使用正确的道具呈现? - How to test if a component is rendered with the right props when using react-testing-library? 有没有人成功地使用 react-testing-library 来测试 draftJS Editor 组件上的更改事件? - Has anyone successfully used react-testing-library to test change events on a draftJS Editor component? 使用React,Jest,React-Testing-Library测试失败的案例 - Test failing cases with React, Jest, React-Testing-Library React-testing-library:在组件上下文中找不到“商店” - React-testing-library: Could not find "store" in the context of component 如何测试在 react-testing-library 中调用了函数 prop - How to test that a function prop was called in react-testing-library React-Testing-Library 中的 Content.Provider 测试失败 - Test fails with Content.Provider in React-Testing-Library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM