zarm
Version:
基于 React 的移动端UI库
63 lines (57 loc) • 2.61 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import useMutationObserverRef from "../hooks/useMutationObserverRef";
describe("useMutationObserverRef", function () {
it("should watch for children change", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var id, fn, TestComp, button;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
id = 1;
fn = jest.fn();
TestComp = function TestComp() {
var _useMutationObserverR = useMutationObserverRef(function (records) {
// 重置监听状态
records.forEach(function (record) {
var _Array$from;
if (((_Array$from = Array.from(record.addedNodes)) === null || _Array$from === void 0 ? void 0 : _Array$from.length) >= 1) {
fn();
}
});
}),
_useMutationObserverR2 = _slicedToArray(_useMutationObserverR, 2),
ref = _useMutationObserverR2[0],
setNode = _useMutationObserverR2[1];
var addTodo = function addTodo() {
var todo = document.createElement("li");
id += 1;
todo.textContent = "todo ".concat(id);
ref === null || ref === void 0 ? void 0 : ref.appendChild(todo);
};
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("ul", {
ref: setNode
}, /*#__PURE__*/React.createElement("li", null, "todo ", id)), /*#__PURE__*/React.createElement("button", {
onClick: addTodo,
type: "button"
}, "Add Todo"));
};
render( /*#__PURE__*/React.createElement(TestComp, null));
button = screen.getByText(/add todo/i);
fireEvent.click(button);
expect(screen.getAllByRole("listitem")).toHaveLength(2);
_context.next = 9;
return waitFor(function () {
expect(fn).toBeCalledTimes(1);
});
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
})));
});