UNPKG

react-testing-library

Version:

Simple and complete React DOM testing utilities that encourage good testing practices.

87 lines (70 loc) 2.3 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _react = _interopRequireDefault(require("react")); var _ = require("../"); afterEach(_.cleanup); class StopWatch extends _react.default.Component { constructor(...args) { super(...args); this.state = { lapse: 0, running: false }; this.handleRunClick = () => { this.setState(state => { if (state.running) { clearInterval(this.timer); } else { const startTime = Date.now() - this.state.lapse; this.timer = setInterval(() => { this.setState({ lapse: Date.now() - startTime }); }); } return { running: !state.running }; }); }; this.handleClearClick = () => { clearInterval(this.timer); this.setState({ lapse: 0, running: false }); }; } componentWillUnmount() { clearInterval(this.timer); } render() { const { lapse, running } = this.state; return _react.default.createElement("div", null, _react.default.createElement("span", null, lapse, "ms"), _react.default.createElement("button", { onClick: this.handleRunClick }, running ? 'Stop' : 'Start'), _react.default.createElement("button", { onClick: this.handleClearClick }, "Clear")); } } const wait = time => new Promise(resolve => setTimeout(resolve, time)); test('unmounts a component', async () => { jest.spyOn(console, 'error').mockImplementation(() => {}); const { unmount, getByText, container } = (0, _.render)(_react.default.createElement(StopWatch, null)); _.fireEvent.click(getByText('Start')); unmount(); // hey there reader! You don't need to have an assertion like this one // this is just me making sure that the unmount function works. // You don't need to do this in your apps. Just rely on the fact that this works. expect(container.innerHTML).toBe(''); // just wait to see if the interval is cleared or not // if it's not, then we'll call setState on an unmounted component // and get an error. // eslint-disable-next-line no-console await wait(() => expect(console.error).not.toHaveBeenCalled()); });