【问题标题】:React test with Jest - onChange never called for Checkbox使用 Jest 进行反应测试 - onChange 从未调用过 Checkbox
【发布时间】:2020-06-05 21:31:39
【问题描述】:

为什么复选框上的 onChange 的 expect() 不起作用?

我正在尝试编写一个测试,以确保当用户更改复选框的状态时调用 onChange 函数。我是使用 React 与 Jest 一起工作的新手,我看不出有什么问题。任何帮助和工作示例都会很好。 Tnx。

Checkbox.js:

import React from 'react';

function Checkbox(props) {

    const { checked, onChange } = props;

    return (
        <input onChange={(e) => onChange(e)} checked={checked} type="checkbox" />
    )
}

export default Checkbox;

Checkbox.test.js:

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import Checkbox from "./index";

let container = null;
beforeEach(() => {
    // setup a DOM element as a render target
    container = document.createElement("div");
    document.body.appendChild(container);
});

afterEach(() => {
    // cleanup on exiting
    unmountComponentAtNode(container);
    container.remove();
    container = null;
});

it("Checkbox onChange fires", () => {

    // Mock props
    const props = {
        onChange: jest.fn(),
        checked: true
    };

    // Render the component
    act(() => { render(<Checkbox {...props} />, container); });

    // Find the component
    const component = container.querySelector('input');

    // onChange Checkbox
    act(() => { component.dispatchEvent(new Event("change", { bubbles: true })); });
    expect(props.onChange).toHaveBeenCalledTimes(1);
});

测试结果:

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

【问题讨论】:

    标签: javascript reactjs jestjs create-react-app onchange


    【解决方案1】:

    工作修复。 问题是组件“onChange”导致 React 重新渲染组件。

    改变这一行:

    act(() => { component.dispatchEvent(new Event("change", { bubbles: true })); }
    

    进入:

    await act( async() => { Simulate.change(component) });
    

    当然还有使测试成为异步函数:

    it("Checkbox renders corretly", async () => {...}
    

    修复了问题。

    【讨论】:

      猜你喜欢
      • 2015-09-10
      • 2020-05-25
      • 1970-01-01
      • 2020-03-07
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多