|
| 1 | +import test from "ava"; |
| 2 | +import fetchMock from "fetch-mock"; |
| 3 | +import { send } from "../../../src/django_unicorn/static/unicorn/js/messageSender.js"; |
| 4 | +import { getComponent } from "../utils.js"; |
| 5 | + |
| 6 | +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 7 | + |
| 8 | +test("loading delay shows after timeout", async (t) => { |
| 9 | + const html = ` |
| 10 | + <div unicorn:id="5jypjiyb" unicorn:name="text-inputs" unicorn:checksum="GXzew3Km"> |
| 11 | + <button unicorn:click='test()' u:loading.class="loading" u:loading.delay-100></button> |
| 12 | + </div>`; |
| 13 | + const component = getComponent(html); |
| 14 | + const { el } = component.actionEvents.click[0].element; |
| 15 | + |
| 16 | + // Initial state: not loading |
| 17 | + t.is(el.classList.length, 0); |
| 18 | + |
| 19 | + // Trigger click |
| 20 | + el.click(); |
| 21 | + |
| 22 | + // Immediately after click: still not loading (because of delay) |
| 23 | + t.is(el.classList.length, 0); |
| 24 | + |
| 25 | + // Wait 50ms (less than 100ms): still not loading |
| 26 | + await delay(50); |
| 27 | + t.is(el.classList.length, 0); |
| 28 | + |
| 29 | + // Wait 100ms more (total 150ms): should be loading |
| 30 | + await delay(100); |
| 31 | + t.is(el.classList.length, 1); |
| 32 | + t.is(el.classList[0], "loading"); |
| 33 | +}); |
| 34 | + |
| 35 | +test("loading delay does not show if action takes less time", async (t) => { |
| 36 | + const html = ` |
| 37 | + <div unicorn:id="5jypjiyb" unicorn:name="text-inputs" unicorn:checksum="GXzew3Km"> |
| 38 | + <button unicorn:click='test()' u:loading.class="loading" u:loading.delay-200></button> |
| 39 | + </div>`; |
| 40 | + const component = getComponent(html); |
| 41 | + const { el } = component.actionEvents.click[0].element; |
| 42 | + |
| 43 | + // Trigger click |
| 44 | + el.click(); |
| 45 | + |
| 46 | + // Immediately after click: not loading |
| 47 | + t.is(el.classList.length, 0); |
| 48 | + |
| 49 | + // Mock fetch to return quickly (e.g. 50ms) |
| 50 | + // We mock a delay in the mock response using delay() inside the response if possible, |
| 51 | + // or just use fetchMock delay option. |
| 52 | + global.fetch = fetchMock.sandbox().mock().post("/test/text-inputs", { |
| 53 | + body: {}, |
| 54 | + delay: 50, // 50ms delay |
| 55 | + }); |
| 56 | + |
| 57 | + // Execute send (simulating the action completing) |
| 58 | + // send returns a promise that resolves when the action is done |
| 59 | + const sendPromise = send(component); |
| 60 | + |
| 61 | + // Wait 100ms (total from start > 50ms response time but < 200ms loading delay) |
| 62 | + await delay(100); |
| 63 | + |
| 64 | + // loading should NOT have shown because action finished at 50ms |
| 65 | + // Check if class is present |
| 66 | + t.is(el.classList.length, 0); |
| 67 | + |
| 68 | + await sendPromise; |
| 69 | + fetchMock.reset(); |
| 70 | +}); |
0 commit comments