我使用mocha和react-testing-library在jsdom中使用带有呈现input
元素的react组件运行测试。
通过change
向input element
发送fireEvent
事件时,将不会触发事件处理程序,也称为onChange={hanldeChange}
。但是,当将自定义eventListener附加到input
元素时,侦听器会做出响应。
我尝试了其他事件,例如click
(onClick)和input
(onInput),一切正常。
这可能是mocha框架中设置的问题。我尝试过开玩笑,它在本地和浏览器(codesandbox)中都可以正常工作。
// InputComp.js
const InputComp = props => (
<div>
<label htmlFor="cost">Item Cost</label>
<input id="cost" onChange={props.handleChange} type="text" />
</div>
);
// inputComp.test.js
import sinon from "sinon";
import InputComp from "./InputComp";
describe("test", () => {
const spy = sinon.spy();
const spyForListener = sinon.spy();
let input;
before(() => {
const wrapper = render(<InputComp handleChange={spy} />);
input = wrapper.getByLabelText("Item Cost");
input.addEventListener("change", spyForListener);
});
afterEach(() => {
spy.resetHistory();
spyForListener.resetHistory();
});
after(() => {
cleanup();
});
it("spyListener is called when 'change' fired", () => {
fireEvent.change(input, {
target: { value: "101" }
});
expect(spyForListener.callCount).toEqual(1);
});
it("spy is not called when 'change' fired", async (done) => {
fireEvent.change(input, {
target: { value: "102" }
});
await (() => {
expect(spy.callCount).toEqual(1);
}).then(done);
});
});
import { JSDOM } from 'jsdom'
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
global.document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}
copyProps(window, global);
测试代码和组件位于codeandbox上: https://codesandbox.io/embed/0p1oow7w5n