为什么复选框上的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
答案 0 :(得分:1)
工作修复。 问题是组件'onChange'导致React重新渲染该组件。
更改此行:
act(() => { component.dispatchEvent(new Event("change", { bubbles: true })); }
进入:
await act( async() => { Simulate.change(component) });
当然也使测试成为异步功能:
it("Checkbox renders corretly", async () => {...}
解决了该问题。