Javascript 测试react.js应用程序时无法将鼠标事件分派到选定元素
正在尝试测试接受事件处理程序的基本react组件Javascript 测试react.js应用程序时无法将鼠标事件分派到选定元素,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,正在尝试测试接受事件处理程序的基本react组件onClick。传入jest.fn()时,测试在expect(myComponent).toHaveBeenCalledTimes(1)上失败。我正在尝试使用以下命令模拟用户单击: const button = document.querySelector("#calcButton"); button.dispatchEvent(new MouseEvent("click", { bubbles: true })); 完整代码如下 该应用程序在p
onClick
。传入jest.fn()
时,测试在expect(myComponent).toHaveBeenCalledTimes(1)
上失败。我正在尝试使用以下命令模拟用户单击:
const button = document.querySelector("#calcButton");
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
完整代码如下
该应用程序在prod和dev以及document.querySelector(“#calcButton”).dispatchEvent(新的MouseEvent(“单击“,{bubbles:true}”)中正常工作代码>在chrome控制台中工作
编辑:如果我将dispatchEvent(…)
替换为,则结果相同。单击()。当单击时,传入console.log(“回调已激活”)
表明回调确实被调用
// calculate-button.test.js
import React from "react";
import { act } from "react-dom/test-utils";
import { render, unmountComponentAtNode } from "react-dom";
import Button from "react-bootstrap/Button";
import CalculateButton from "./calculate-button";
let container = null;
beforeEach(() => {
// setup a DOM element as a render target
container = document.createElement("div");
document.body.appendChild(container);
});
// Omitted afterEach and some other tests. The problem occurs with them commented out.
it("fires event when clicked.", () => {
const clicked = jest.fn();
act(() => {
render(<CalculateButton onClick={clicked} />, container);
});
const button = document.querySelector("#calcButton");
console.log(button); // Output indictates button is being selected as hoped.
act(() => {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
expect(clicked).toHaveBeenCalledTimes(1);
// This is where the error happens.
});
我明白了。谢谢你的帮助
在calculate button.js
I referenceonClick={props.handleClick}
中,但在calculate button.test.js
中,我将mockClickHandler
作为prop
onClick
传递。通过更改render(,container)来更改不匹配代码>到渲染(,容器)代码>修复了它
这就是我草率命名的原因。再次感谢。您试过按钮了吗?单击()谢谢,@MattOestreich。我去看看。我确实认为应该执行jest.fn()
,因为将其他函数传递到onClick=
可以证明它们被调用。按钮。单击()
会产生相同的结果。
//calculate-button.js
import React from "react";
import Button from "react-bootstrap/Button";
function calculateButton(props) {
return (
<Button
variant="primary"
size="lg"
id="calcButton"
block
onClick={props.handleClick}
>
Calculate!
</Button>
);
}
export default calculateButton;
● Console
console.log src/components/calculate-button/calculate-button.test.js:36
HTMLButtonElement {
'__reactInternalInstance$vwtourl9fj':
FiberNode {
tag: 5,
key: null,
elementType: 'button',
type: 'button',
stateNode: [Circular],
return:
...OMITTED...
● fires event when clicked.
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
39 | });
40 |
> 41 | expect(clicked).toHaveBeenCalledTimes(1);
| ^
42 | });
43 |
at Object.toHaveBeenCalledTimes (src/components/calculate-button/calculate-button.test.js:41:19)
Test Suites: 1 failed