简体   繁体   中英

React test with Jest - onChange never called for Checkbox

Why is expect() for onChange on a checkbox not working?

I'm trying to write a test to make sure that the onChange function gets called when a user changes the state of a checkbox. I'm new to working with Jest with React and i don't see what could be wrong. Any help and working example would be nice. 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);
});

Test result:

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

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

Working fix. Problem was the component 'onChange' was causing React to re-render the component.

Changing this line:

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

into:

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

and ofcourse making the test a async function:

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

fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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