reblend-testing-library
Version:
Simple and complete Reblendjs testing utilities that encourage good testing practices.
81 lines (80 loc) • 3 kB
JavaScript
import Reblend, { useEffect, useState } from "reblendjs";
import { render, waitForElementToBeRemoved, screen, waitFor } from "../";
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 Reblend {
static ELEMENT_NAME = "ComponentWithMacrotaskLoader";
constructor() {
super();
}
async initState() {
const [state, setState] = useState.bind(this)({
data: undefined,
loading: true
}, "state");
this.state.state = state;
this.state.setState = setState;
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 ? Reblend.construct.bind(this)("div", null, "Loading...") : Reblend.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 render(Reblend.construct.bind(this)(ComponentWithMacrotaskLoader, null));
const loading = () => screen.getByText("Loading...");
await waitForElementToBeRemoved(loading);
await waitFor(() => {
expect(screen.getByTestId("message")).toHaveTextContent(/Hello World/);
});
});
test("waitFor", async () => {
await render(Reblend.construct.bind(this)(ComponentWithMacrotaskLoader, null));
await waitFor(() => screen.getByText(/Loading../));
await waitFor(() => screen.getByText(/Loaded this message:/));
await waitFor(() => {
expect(screen.getByTestId("message")).toHaveTextContent(/Hello World/);
});
});
test("findBy", async () => {
await render(Reblend.construct.bind(this)(ComponentWithMacrotaskLoader, null));
await waitFor(async () => {
await expect(screen.findByTestId("message")).resolves.toHaveTextContent(/Hello World/);
});
});
});