【问题标题】:Why isn't the click fireEvent being called?为什么不调用 click fireEvent?
【发布时间】:2021-11-22 08:31:16
【问题描述】:

我正在尝试使用 onClick 属性调用模拟函数,并使用 React 测试库进行测试。测试是我正在努力改进的东西,但就我目前所拥有的了解而言。

我正在测试的是当单击按钮时调用一个函数,我正在渲染作为道具传递函数的组件(样式化组件)。

(它自己的函数是异步的,但是因为我只是在嘲笑按钮上正在调用一个函数,所以我只是使用 getBy)

测试文件

import { render, screen, fireEvent } from "@testing-library/react";
import QuoteButton from "../Components/QuoteButton";

test("fire event from QuoteButton component", () => {
    const mockCollect = jest.fn();
    render(<QuoteButton onClick={mockCollect}>get a quote</QuoteButton>);
    const buttonElement =  screen.getByRole("button", { name: /get a quote/i });
    fireEvent.click(buttonElement);
    expect(mockCollect).toHaveBeenCalledTimes(1);
  });

组件

import styled from 'styled-components'

const StyledButton = styled.button`
    cursor: pointer;
    background: transparent;
    font-size: 18px;
    border-radius: 3px;
    border-color: #f9a800;

    &:hover {
        background-color: #ff7800;
        color: #fbfbf8
    }
`
const QuoteButton = ({ children, collect }) => {
    return <StyledButton data-testid="quoteButton" onClick={collect}>{children}</StyledButton>
}

export default QuoteButton

它正在接收 0 个呼叫,还有什么我应该寻找或测试的吗?任何帮助表示赞赏。我的理解是,因为我正在用 jest.fn() 模拟一个函数,所以必须有一些东西通过。

【问题讨论】:

    标签: javascript reactjs testing jestjs react-testing-library


    【解决方案1】:

    您有一个名为 collect 的道具没有在您的测试中通过,而是您使用的是 onClick

    import { render, screen, fireEvent } from "@testing-library/react";
    import QuoteButton from "../Components/QuoteButton";
    
    test("fire event from QuoteButton component", () => {
        const mockCollect = jest.fn();
        {/* Wrong: QuoteButton uses 'collect' as a prop */}
        // render(<QuoteButton onClick={mockCollect}>get a quote</QuoteButton>);
    
        {/* Right: collect will be the prop passed to your internal component's 'onClick' */}
        render(<QuoteButton collect={mockCollect}>get a quote</QuoteButton>); // --> 
        const buttonElement =  screen.getByRole("button", { name: /get a quote/i });
        fireEvent.click(buttonElement);
        expect(mockCollect).toHaveBeenCalledTimes(1);
      });
    

    在您在 &lt;QuoteButton&gt;collect 属性中定义的原始代码中,然后将其传递给您的 &lt;button&gt;onClick,您基本上是在说:onClick -> call collect's请参考。

    由于在您的规范中您没有向&lt;QuoteButton&gt; 发送任何要收集的内容,因此在您的规范中没有什么可调用的。此外,由于您没有对收到的onClick 进行任何操作,因此它也不会改变任何内容。

    【讨论】:

    • 我看到现在很棒,非常感谢您的解决方案和解释。
    猜你喜欢
    • 2012-03-31
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多