UNPKG

reblend-testing-library

Version:

Simple and complete Reblendjs testing utilities that encourage good testing practices.

83 lines (81 loc) 3.11 kB
"use strict"; var _reblendjs = require("reblendjs"); var _ = require("../"); describe.each([["real timers", () => jest.useRealTimers()], ["fake legacy timers", () => jest.useFakeTimers("legacy")], ["fake modern timers", () => jest.useFakeTimers("modern")]])("it waits for the data to be loaded in a macrotask using %s", (label, useTimers) => { beforeEach(() => { useTimers(); }); afterEach(() => { jest.useRealTimers(); }); const fetchAMessageInAMacrotask = () => new Promise(resolve => { // we are using random timeout here to simulate a real-time example // of an async operation calling a callback at a non-deterministic time const randomTimeout = Math.floor(Math.random() * 100); setTimeout(() => { resolve({ returnedMessage: "Hello World" }); }, randomTimeout); }); //@reblendComponent class ComponentWithMacrotaskLoader extends _reblendjs.default { static ELEMENT_NAME = "ComponentWithMacrotaskLoader"; constructor() { super(); } async initState() { const [state, setState] = _reblendjs.useState.bind(this)({ data: undefined, loading: true }, "state"); this.state.state = state; this.state.setState = setState; _reblendjs.useEffect.bind(this)(() => { let cancelled = false; fetchAMessageInAMacrotask().then(data => { if (!cancelled) { this.state.setState({ data, loading: false }); } }); return () => { cancelled = true; }; }, (() => []).bind(this)); } async initProps() { this.props = {}; } async html() { return this.state.state.loading ? _reblendjs.default.construct.bind(this)("div", null, "Loading...") : _reblendjs.default.construct.bind(this)("div", { "data-testid": "message" }, "Loaded this message: ", this.state.state.data.returnedMessage, "!"); } } /* @Reblend: Transformed from function to class */ test("waitForElementToBeRemoved", async () => { await (0, _.render)(_reblendjs.default.construct.bind(this)(ComponentWithMacrotaskLoader, null)); const loading = () => _.screen.getByText("Loading..."); await (0, _.waitForElementToBeRemoved)(loading); await (0, _.waitFor)(() => { expect(_.screen.getByTestId("message")).toHaveTextContent(/Hello World/); }); }); test("waitFor", async () => { await (0, _.render)(_reblendjs.default.construct.bind(this)(ComponentWithMacrotaskLoader, null)); await (0, _.waitFor)(() => _.screen.getByText(/Loading../)); await (0, _.waitFor)(() => _.screen.getByText(/Loaded this message:/)); await (0, _.waitFor)(() => { expect(_.screen.getByTestId("message")).toHaveTextContent(/Hello World/); }); }); test("findBy", async () => { await (0, _.render)(_reblendjs.default.construct.bind(this)(ComponentWithMacrotaskLoader, null)); await (0, _.waitFor)(async () => { await expect(_.screen.findByTestId("message")).resolves.toHaveTextContent(/Hello World/); }); }); });